简体   繁体   中英

Post data with ajax to java servlet

First of all, pardon me if my english is bad. I'm having some problems with sending data to my ExportServlet with ajax.

ExportServlet.java

public class ExportServlet extends HttpServlet {
private static final long serialVersionUID = 6715605810229670146L;

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String fileName = req.getParameter("filename");

    //Create ZIP file
    try {
        res.setContentType("applicatin/zip");
        res.setStatus(HttpServletResponse.SC_OK);

        ZipOutputStream zos = new ZipOutputStream(res.getOutputStream());

        //Create TXT file
        zos.putNextEntry(new ZipEntry(fileName + ".txt"));
        zos.write(getOutputData());
        zos.closeEntry();

        zos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private byte[] getOutputData() {
    byte[] result = null;
    String tmp = "Text file content";
    result = tmp.getBytes();
    return result;
}
}

The java code above works absolutely perfect.

Then I have my ajax code that sends data to my ExportServlet (I have used filename for an example):

//Post data to ExportServlet
        $.ajax({
            type: 'post',
            url: '/export.zip',
            data: "filename = myFile",
            success:function(data){alert(data);},
            error:function(){alert('error');}
        });

The problem is that when the ajax function is triggered I get an error callback. I also have a link to download the ZIP file generated by ExportServlet:

<a href="/export.zip">Download file</a>

And indeed, when I click the link I get ZIP file with "null.txt" in it. How can I fix this?

Thanks alot in advance!

Try this:

<a href="javascript:;" onclick="downloadFile();">Download file</a>
<div style="display: none;">
   <iframe id="downloadFileFrame"></iframe>
</div>


function downloadFile() {
    $('#downloadFileFrame').attr('src','/export.zip?filename=myFile');
    return false;
}

When you click on the link, the ajax code will not be called so the filename parameter will not be included in the request to the servlet. The servlet will execute with filename = null. That is the actual result you got.

To fix this, I think you have to call the ajax code at the first time the page loaded so that your servlet can create a file and place it on the server. Then you have to pass filename parameter in your link such as:

<a href="http://yourdomain.com/downloadFile?filename=myFile">Download file</a>

The downloadFile servlet will look for file named myFile.txt which was created at the first time your page loaded with ajax called, and give you the file in response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM