Commons文件上传

时间:2014-10-16 14:08:10

标签: javascript jquery ajax jsp

我正在尝试使用apache commons文件上传库从jsp / ajax上传文件。以下是代码:

JSP:

function importFileListForm()  
{
var html = "<div><h3>Add File</h3></div>";
html += '<table style="margin-top:20px;" width="100%"><tbody>'; 
html += '<tr><td>Choose File</td><td><input id="fileId" type="file" name="fileName" required size="50"/></td><td></td></tr>';
html += '</tbody></table>';

$("#dialog-modal-content").html(html);
$(function() {
    $( "#dialog-modal" ).dialog({
      height: 300,
      width: 600,
      modal: true,
      buttons: {
        "Cancel": function() {
            $(this).dialog("close");
        },
        "Submit": function() {
            importFileConfirm($("#fileId").val());
        }
      }
    }); 
});
}

function importFileConfirm(file)
{
var url = "/config/fileManageAction.do?method=importFile&file=" +file;
var req = new FormData();
req.append("f", file);
$.ajax({
    type: 'POST',
    data: req,
    url: url,
    processData: false,
    contentType: false,
    success: function(data) {console.log(data);}

});
}

我在动作类中的方法:

      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setSizeThreshold(maxSize);
      factory.setRepository(new File("/production/cpu/temp.xlsx"));

      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxSize );
      try{
          List fileItem = upload.parseRequest(request);
          java.lang.System.out.println("List  "+fileItem.size());

    //    Part filePart = request.getPart("file");
    //    java.lang.System.out.println("File Part "+filePart);

         // Process the uploaded file items
          Iterator i = fileItem.iterator();
          while(i.hasNext()){
              FileItem fi = (FileItem)i.next();
              if(!fi.isFormField()){
                  java.lang.System.out.println("Fi "+fi);
                  String fieldname = fi.getFieldName();
                  java.lang.System.out.println("FieldName "+fieldname);
                  String filename =  FilenameUtils.getName(fi.getName());
                  java.lang.System.out.println("File Name "+fi.getString());
                  InputStream filecontent = fi.getInputStream();
              }else{
                  java.lang.System.out.println("not a form field");
                  java.lang.System.out.println("Fi "+fi);
                  String fileName = fi.getName();
                  java.lang.System.out.println("File Name: "+fileName);
              }


          }
      }catch(Exception e){
          java.lang.System.out.println("Exception occured "+e);
          e.printStackTrace();
      }

 //   }

 }

但在我的文件项中,我只获取字段名称,fi.getName()返回null。有人可以对我所缺少的东西有所了解吗?。

我无法使用getParts()函数,因为我的tomcat不支持它。

1 个答案:

答案 0 :(得分:0)

您必须将File对象添加到FormData对象。 $("#fileId").val()为您提供文件名,以使文件使用$("#fileId")[0].files[0]

req.append("f", $("#fileId")[0].files[0]);