简体   繁体   English

在Servlet中上传Excel

[英]Uploading excel in servlet

I'm trying to upload an excel in servlet and process it. 我正在尝试上载servlet中的excel并对其进行处理。 While uploading I set enctype=“multipart/form-data” in my form. 上传时,我在表单中设置了enctype =“ multipart / form-data”。 But in my servlet .isMultiPart(request) returns false. 但是在我的servlet中,.isMultiPart(request)返回false。

JSP code: JSP代码:

function fSubir() 函数fSubir()

{

fFreezeButtons();

this.document.forms[0].action="../servlet/renault.saf.demandepiece.demandes.servlet.AjouterPoste";

if (this.document.forms[0].Flag.value == "1")

{

this.document.forms[0].Flag.value = "0";

this.document.forms[0].submit();

}

} }

Select .xlsx type File : 选择.xlsx类型File:

<input type="submit" value="upload" onclick="fSubir()"/>

My .Jsp also has another form of get method which doesn't have any enctype. 我的.Jsp也有另一种get方法,它没有任何enctype。

Servlet code; Servlet代码;

public class AjouterPoste extends SapprServlet{ 公共类AjouterPoste扩展了SapprServlet {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private final String UPLOAD_DIRECTORY = "/appli01/safdev01/saf_cl2/test/";

public void performTask(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    try {
        System.out.println("inside the AjouterPoste class - performTask");
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        System.out.println("Inside doPost:"+isMultipart+":"+request);

Please find the parts of my code on which I'm trying to upload a file. 请找到我要上传文件的代码部分。

When you submit a form having multipart/form-data , you can't use request.getParameter(paramName) . 提交具有multipart/form-data ,不能使用request.getParameter(paramName) Instead use the code below (part of the Apache FileUpload library) 而是使用下面的代码( Apache FileUpload库的一部分)

try {
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // this part is used instead of request.getParameter
                String fieldName = item.getFieldName();
                String fieldValue = item.getString();
                // do something here
            } else {
                // this is the file processing part
                String fieldName = item.getFieldName();
                String fileName = FilenameUtils.getName(item.getName());
                InputStream fileContent = item.getInputStream();
       ...
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("exception", e);
    }

You can tell that a specific item is a regular form item (and not a file) by checking that FileItem.isFormField() method returns true . 通过检查FileItem.isFormField()方法是否返回true可以确定特定项目是常规表单项目(而不是文件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM