使用ajax和java servlet上传文件

5

我正在尝试使用一个继承了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页面中,我有一个表格内的表单:

<form method="post" action="CSRUploadListServlet" enctype="multipart/form-data">
<input type="file" name="custIdList" id="custIdList" />
<input type="submit" value="Upload" class="upldBtn" />
</form>

在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= {} ", methodName, 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 = {} ", methodName,
                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: {} ", methodName, ex);
    }
    getServletContext().getRequestDispatcher(
            "/WEB-INF/web/csrCustomerLists/message.jsp").forward(request,
            response);
}

所有问题都停留在if (!ServletFileUpload.isMultipartContent(request)),返回错误信息:'Request does not contain upload data'。

我确定我的ajax写得不正确,但是我似乎找不到错在哪里。

谢谢。


当您按下提交按钮时,为什么会调用 CSRUploadListServletcontextPath + servletPath - user2948112
是的,在我按下上传提交按钮时使用Servlet。 - Razvan N
你不能像这样通过Ajax上传文件。你把文件当作普通参数来处理是不行的。这样做不起作用。请参阅https://dev59.com/aHI-5IYBdhLWcg3wwbdM。 - developerwjk
好的,我现在明白了,谢谢。但是如果我避免使用Ajax,那么表单就无法通过servlet访问。 - Razvan N
1个回答

4

嘿!尝试以不同的方式放置您的html代码,然后从ajax调用servlet,就像您在那里做的那样。我认为问题可能出在您正在使用的表单上,即重写某些属性或类似的东西。

我建议使用从js代码加载的iframe选项。 html代码可以像这样:

<button id="upldBtn" title="Upload" >Do the upload</button>

<div id="textarea" style="display: none;"></div>

<input type="file" class="file" id="file" name="file" title="Please upload"/>

以下是JavaScript代码:

    $(function() { 

    $('#upldBtn').click(function() {
        var contextPath = 'your path string';
        var servletName = 'your servlet name string';
        var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none" />');
        $("body").append(iframe);

         $("form#yourform").attr('action', contextPath+servletName);
         $("form#yourform").attr('enctype', "multipart/form-data");
         $("form#yourform").attr("target", "postiframe");
         $("form#yourform").attr("file", $('#file').val());

        $('yourform').submit(); //upload button 
             $("#postiframe").load(function () {
                    iframeContents = $("#postiframe")[0].contentWindow.document.body.innerHTML;
                    $("#textarea").html(iframeContents);
                            $.ajax({
                                    type: "GET",
                                    url: contextPath+servletName,
                                    data: "action=download",
                                    async: false,
                                    dataType: "text",
                                    success: function(result) {
                                        //do something
                                    }
                                });
                } });
            }); 
});

告诉我是否对您来说没问题。 :)祝好

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接