【问题标题】:apache.commons.fileupload not working with jquery.ajaxapache.commons.fileupload 不适用于 jquery.ajax
【发布时间】:2016-10-29 07:20:26
【问题描述】:

我是 JSP 和 Servlet 的新手,我正在尝试上传单个文件并使用 jQuery.ajax() 将其移动到我的目录中。当我将action="servletName" 放入没有ajax 的表单中时,它工作正常,我认为我的servlet 工作正常(我什至使用JSP 尝试过,它也很好)。但是,当我使用 ajax 时,它什么也没做。我还尝试在 PHP 中使用相同的 ajax 代码,并且 PHP 中的所有内容都运行良好。

顺便说一句,这是我的代码:

HTML 表单

<form method="POST" enctype="multipart/form-data" id="frmFile">
        <input type="file" name="file"/>
        <input type="submit" name="submit" value="Submit"/>
    </form>

JS

var fd = new FormData();

$("#frmFile").submit(function(){
   $.ajax({

       type: 'post',
       url: '../init.jsp',
       data: fd,
       processData: false,
       cache: false,
       contentType: false,
       async: true, //with or without
       success: function(data){
           alert(data);
       }           
   });
   return false;
});

Servlet

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;

public class init extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if(isMultiPart){
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            String path;
            //path = getServletContext().getRealPath("")+"assets\\uploads";
            path = "C:/Users/M/Desktop";
            try{
                List<FileItem> fileItems = upload.parseRequest(request);

                for(FileItem items: fileItems){
                    if(!items.isFormField()){
                        String name = new File(items.getName()).getName();
                        items.write(new File(path+File.separator+name));
                    }                        
                }
                out.print("SUCCESSFUL!");
            }catch(Exception e){

            }
        }else{
            out.print("!multipart");
        }
    }
}
//doGet, doPost, getServletInfo

此外,我也相信我的 ajax 可以正常工作,因为除此之外它还可以与 PHP 一起使用。它打印(警告)“成功!”这是在 servlet 的 try-block 中编码的。

我的问题是我的 servlet 代码中是否缺少某些内容?或者 apache.commons.fileupload 只是阻止 ajax 请求?

谢谢!

【问题讨论】:

  • 你是说你的 Servlet 用“成功!”这个词来响应。 ?也许您应该在响应中添加更多打印语句。也许打印文件名和绝对路径及其大小。
  • Loos 像解析问题,formData 没有被 commons 解析。在任何事情之前我会建议你尝试 jquery ajaxfileupload 插件以确保

标签: jquery ajax jsp servlets apache-commons-fileupload


【解决方案1】:

可能在 ajax 中缺少以下内容: encType : "multipart/form-data"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-09
    • 2012-10-14
    • 2013-09-16
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    相关资源
    最近更新 更多