其他分享
首页 > 其他分享> > 如何使用multipart / form-data发布ajax调用?

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

作者:互联网

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

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代码:

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>");
                } 

                ..... 
             }
          }

解决方法:

您无法使用AJAX上传文件.

Ext的Ajax可以模仿它.请参阅doc of the request方法.您必须使用表单和isUpload选项.

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

编辑:事实上,HTML5 and XMLHttpRequest Level 2增加了对文件上传的支持.但是,不会改变你在Ext中处理它的方式.

标签:java,ajax,extjs,servlets,apache-commons
来源: https://codeday.me/bug/20190825/1721392.html