java 如何使用 multipart/form-data 发布 ajax 调用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17055532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:49:44  来源:igfitidea点击:

How to post ajax call with multipart/form-data?

javaajaxservletsextjsapache-commons

提问by JS11

I need to upload a file from extjs page, via AJAX call, to the server. I am able to do it with simple HTML page to servlet but using extjs (v4.0.7) i am not getting file in my servlet when i pars request. Servlet recognizes multipart page but nothing comes with the call. Can anyone tell me what I am doing wrong in my code?

我需要通过 AJAX 调用从 extjs 页面上传文件到服务器。我可以使用简单的 HTML 页面到 servlet 来做到这一点,但是使用 extjs (v4.0.7) 我在解析请求时没有在我的 servlet 中获取文件。Servlet 识别多部分页面,但调用没有任何内容。谁能告诉我我的代码做错了什么?

EXTJS code:

EXTJS代码:

var fileName = Ext.getCmp("fileName").getValue();

Ext.Ajax.request({
    url : 'UploadServlet',
    method: 'POST',  
    headers: {'Content-Type': 'multipart/form-data'},
    params :{
       'fileName': fileName.trim()
    },

    success: function ( result, request ) {
        resultData = result.responseText;
    },
    failure: function ( result, request ) {
        resultData = result.responseText;
    }   
});

Servlet code:

服务端代码:

protected void doPost(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, IOException {  

    .......

     // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
      if( !isMultipart ){
          // display no file attached error
         return;
      }

      // Create a factory for disk-based file items
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File(tempDir));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );


      try{ 
          // Parse the request to get file items.

      ////// fileItems is empty, 
              ////nothing is comming from extjs page/////////
          List<FileItem> fileItems = upload.parseRequest(request);

          // Process the uploaded file items
          Iterator<FileItem> i = fileItems.iterator();

          while ( i.hasNext () ) {                
             FileItem fi = (FileItem)i.next();

             if ( !fi.isFormField () ) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                // check if file exists
                File propFile = new File(tempDir, fileName.substring( fileName.lastIndexOf("\")));
                if (!propFile.exists()) {  
                    // Write the file
                    if( fileName.lastIndexOf("\") >= 0 ){
                       file = new File(tempDir + 
                       fileName.substring( fileName.lastIndexOf("\"))) ;
                    }else{
                       file = new File(  tempDir + 
                       fileName.substring(fileName.lastIndexOf("\")+1)) ;
                    }   
                    //InputStream uploadedStream = fi.getInputStream();
                    fi.write( file ) ;
                    out.println("Uploaded Filename: " + fileName + "  is in " + filePath + "<br>");
                } 

                ..... 
             }
          }

回答by rixo

You can't upload a file with AJAX.

您无法使用 AJAX 上传文件。

Ext's Ajaxcan emulate it though. See the doc of the requestmethod. You have to use the formand isUploadoptions.

不过,ExtAjax可以效仿它。请参阅request方法的文档。您必须使用formisUpload选项。

However, since you have to use a form anyway, you should look at Ext.form.field.Field(and, as suggested in the doc, to Ext.form.Basic.hasUpload; that will give you a better understanding of the file upload problematic).

但是,由于无论如何您都必须使用表单,因此您应该查看Ext.form.field.Field(并且,正如文档中所建议的, to Ext.form.Basic.hasUpload; 这将使您更好地了解文件上传问题)。

EDIT:In fact, HTML5 and XMLHttpRequest Level 2adds support for file upload. Doesn't change how you have to handle it in Ext, though.

编辑:事实上,HTML5 和 XMLHttpRequest Level 2添加了对文件上传的支持。但是,不会改变您必须在 Ext 中处理它的方式。