在使用multidata格式上传文件时,从ajax调用获取servel的响应

时间:2015-10-19 11:32:29

标签: javascript java jquery ajax jsp

我的项目有点问题。 嗨有几个jsp&Java和Java类。在一个jsp我创建一个只有输入类型="文件"并输入"提交",然后我有一个ajax调用并将所有formdata发送到我的servel上的doPost类。然后我将该文件发送到DataBase,一切顺利,我的问题是我想将数据库中的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函数上使用该值

1 个答案:

答案 0 :(得分:0)

在servlet的$("li.parent a").click(function(e) { e.stopPropagation(); }); 的第一行中,将响应的内容类型更改为&#34; application / json&#34;。然后将JSON字符串写入输出流。有libraries可以为您执行此操作,但对于这么简单的事情,您可以自己编写JSON。这实际上可能有一个优势,因为您的密钥是java long;将其视为字符串,您不必担心整数的表示方式。

doPost()

然后在成功回调函数中,您可以将密钥作为// replace out.println("success"); with this: out.print("{\"key\": \"" + key + "\"}"); 对象的字段进行访问。您需要在ajax方法(data)中指定数据类型。

dataType: 'json'