jquery – 使用ajax和java servlet上传文件

前端之家收集整理的这篇文章主要介绍了jquery – 使用ajax和java servlet上传文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图使用扩展HttpServlet的servlet从jsp页面上传一个csv文件.在jsp页面中,我使用的是一个应该调用servlet的ajax.

这是ajax部分:

    $(function() {
    $(".upldBtn").click(function() {

        alert("Upload button pushed");

        $.ajax({
            type: "POST",url: contextPath + servletPath,data: "action=get&custIdList=" + $('#custIdList').val(),async: false,dataType: "text/csv; charset=utf-8",success: function(data){
                  alert("success");
              }
        });
    });

contextPath和servletPath也被声明,我没有在这里指定它们.

在jsp页面中,我在表格中有这个表格:

在servlet中,我想使用这个doPost方法

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

    String methodName = "doPost";

    logger.debug("[{}] call",methodName);

    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        logger.debug("[{}] Request does not contain upload data",methodName);
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    logger.debug("[{}] factory= {} ",methodName,factory);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    logger.debug("[{}] upload= {} ",upload);

    // constructs the directory path to store upload file
    String uploadPath = getServletContext().getRealPath("")
            + File.separator + UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
        logger.debug("[{}] upload directory = {} ",uploadDir.mkdir());
    }

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);
            }
        }
        request.setAttribute("message","Upload has been done successfully!");
        logger.debug("[{}] Upload has been done successfully! ",methodName);
    } catch (Exception ex) {
        request.setAttribute("message","There was an error: " + ex.getMessage());
        logger.debug("[{}] There was an error: {} ",ex);
    }
    getServletContext().getRequestDispatcher(
            "/WEB-INF/web/csrCustomerLists/message.jsp").forward(request,response);
}

所有这些都停留在if(!ServletFileUpload.isMultipartContent(request)),返回:’Request不包含上传数据’.

我确信我没有正确地编写ajax,但我似乎无法找出我做错的地方.

谢谢.

最佳答案
喜!尝试以不同的方式放置你的HTML代码,然后从ajax调用servlet,就像你在那里那样.我认为问题可能在于您正在使用的形式,即重写某些属性或类似的东西.

我建议用iframe加载一个选项,从js代码加载.HTML代码可以是这样的:

和javascript代码

    $(function() { 

    $('#upldBtn').click(function() {
        var contextPath = 'your path string';
        var servletName = 'your servlet name string';
        var iframe = $('