【问题标题】:get response from servel on ajax call when uploading file with multidata form使用多数据表单上传文件时从服务器获取 ajax 调用响应
【发布时间】:2016-01-17 17:37:43
【问题描述】:

我的项目有点问题。 您好有几个jsp 和Java 类。在一个jsp中,我创建了一个只有输入type="file"和type="submit"的表单,然后我有一个ajax调用并将所有formdata发送到我的服务器上的doPost类。然后我将该文件发送到数据库,一切都很好,我的问题是我想将 id 从数据库返回到 .jsp。我可以访问并在 doPost 上打印以检查我的密钥,但无法将其发送到 ajax 调用中的成功函数.. 这是我的代码,我真的很感谢任何帮助,谢谢!

<form id="uploadDocuments" target="invisible"  method="POST" action="UploadDocumentsAjaxService" enctype="multipart/form-data">
                    <iframe name="invisible" style="display:none;"></iframe>                    
                    <h3 style="width: 71%;margin-left: 8%;">ANEXAR FICHEIROS:</h3>
                    <h4 style="margin-left: 8%; color: #F7A707" >Escolher ficheiro para anexar: </h4>
                    <input type="file" id="file_input" name="file" size="50" style="width: 60%; margin-left: 8%;"/>
                    <input type="submit" value="Upload" />
                </form> 

我有我的 Ajax 调用:

$("#uploadDocuments").submit(function (e) {
        alert(10);
        alert($("#uploadDocuments").attr('action'));
        $.ajax({
            type: $("#uploadDocuments").attr('method'),
            url: $("#uploadDocuments").attr('action'),
            contentType: $("#uploadDocuments").attr( "enctype"),
            data: new FormData($("#uploadDocuments")[0]),
            processData: true,
            success: function (data) {
                alert("submitDocument");
                alert();
                /* key = data;
                addFilesToTable(key); */
                return true;
            }
        });
        e.preventDefault();
        $(form).off('submit');
        return false;
        });

然后是我的 servlet 类:

protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
    response.setContentType("text/html;charset=ISO-8859-1");

    PrintWriter out = response.getWriter();

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    ChangeEntityRequestActionBean actionBean = new ChangeEntityRequestActionBean();

    if(!isMultipart)
        return;

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + DATA_DIRECTORY;

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);
    String fileName = "";
    Long documentKey = null;
    String key = "";

    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                fileName = new File(item.getName()).getName();
                String filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                item.write(uploadedFile);
            }
            documentKey = actionBean.insertDocument(item, fileName);

            System.out.println("Key from DAO ------->>>>>"+documentKey);
            key = String.valueOf(documentKey);

        }

        System.out.println("Key in String from DAO ----->"+key);
        System.out.println();

        out.println("success");
        response.flushBuffer();
    }catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
  } finally {
      out.close();
  }


}

我想要的只是将键值发送到 out.println 以便我可以在 jquery 函数上使用该值

【问题讨论】:

  • 把它作为 json 老兄发送。
  • 我尝试使用 json 发送密钥,但没有成功

标签: javascript java jquery ajax jsp


【解决方案1】:

在您的servlet 中doPost() 的第一行中,将响应的内容类型更改为“application/json”。然后将 JSON 字符串写入输出流。有 libraries 可以为您执行此操作,但是对于如此简单的事情,您可以自己编写 JSON。这实际上可能有一个优势,因为您的密钥是java long;把它当作一个字符串,你不必担心整数是如何表示的。

// replace out.println("success"); with this:
out.print("{\"key\": \"" + key + "\"}");

然后在成功回调函数中,可以将key作为data对象的一个​​字段来访问。您需要在 ajax 方法中指定数据类型 (dataType: 'json')。

success: function (data) {
    var key = data['key'];
    addFilesToTable(key);
    return true;
}

【讨论】:

  • 有点帮助,谢谢! ;)。但现在它发送字符串 {\"key\": \"" + key + "\"}" 用于文件,IE 询问我是否要打开或保存......我无法获得警报我的成功功能上的一些东西,它似乎永远不会进入那里
  • 嗯,通过查看您的代码,我不确定为什么会发生这种情况。你弄明白了吗?
  • 是的,我只是添加了这三行,它就起作用了:cache: false, contentType: false, processData: false,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-21
  • 1970-01-01
  • 2015-02-12
  • 2011-01-12
  • 2018-04-18
  • 2017-05-17
  • 1970-01-01
相关资源
最近更新 更多