1

I'm with a little problem on my project. Hi have several jsp's and Java class. In one jsp i create a form with only a input type="file" and type="submit", then I have an ajax call and send all the formdata to a doPost class on my servel. Then I send that file to the DataBase and it all's go fine, my problem is I want to return the id from the database to the .jsp. I can access and have prints on the doPost to check my key, but cant send it to success function inside the ajax call.. Here's my code, i really apreciate any kind of help, thanks!

<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> 

the I have my Ajax Call:

$("#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;
        });

And then my servlet class:

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();
  }


}

All I want is to send the key value to out.println so I can use that value on a jquery function

João Maia
  • 13
  • 5

1 Answers1

0

In the first line of doPost() in your servlet, change the content-type of the response to "application/json". Then write a JSON string to the output stream. There are libraries available to do this for you, but for something so simple, you can compose the JSON yourself. This might actually have an advantage because your key is a java long; treat it as a string and you don't have to worry about how the integer is represented.

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

Then in the success callback function, you can access the key as a field of the data object. You'll need to specify the data type in the ajax method (dataType: 'json').

success: function (data) {
    var key = data['key'];
    addFilesToTable(key);
    return true;
}
Community
  • 1
  • 1
Tap
  • 6,332
  • 3
  • 22
  • 25
  • It help a bit, thanks! ;). But now it sends the string {\"key\": \"" + key + "\"}" for a file and IE asks if I want so open or save ... And I can't get a way to alert something on my success function, it seemes it never enters there – João Maia Oct 19 '15 at 14:22
  • Hmm, I'm not sure why that would happen, from looking at your code. Did you figure it out? – Tap Oct 19 '15 at 14:58
  • Yes, I just add this three lines and it worked: cache: false, contentType: false, processData: false, – João Maia Oct 19 '15 at 15:03