always
always

Reputation: 155

Java Servlet File download dialog not showing

I have a web application which let user download a image file from the server. When user hit a button on jsp page a ajax post request is made which executes a servlet and in response sends a image file. But the issue is that image file never downloads and Save As dialog box is not coming up.

In the Firebug I can see that request is send correctly and response was received with the correct Contect Type and status code 200. I can also see binary data in the firebug Response tab but still for some reason image is not downloading. Pls help.

Request: *Request URL:http://localhost:8080/SVGToImage/convertToImg

Request Method:POST

Status Code:200 OK*

Response:

*Content-Disposition:filename="out.jpg"

Content-Type:image/jpeg

Date:Fri, 31 May 2013 17:28:26 GMT

Server:Apache-Coyote/1.1

Transfer-Encoding:chunked*

Here is my JSP

<head>

<script>

    function exportToImage(){

    var svg = document.getElementById("ext-gen1040");       

    var svg1 = new XMLSerializer().serializeToString(svg);

        jQuery.noConflict();

        jQuery.ajax({
            url: "convertToImg" ,
            type: "POST",
                    data: { q = svg1},
            success: function(data) {               
            },
          error: function(jqXHR, textStatus, errorThrown) {
              alert('Error ' + textStatus);
          }     
});

</script>

</head>

<body>
<input type="button" value="export" onclick="javascript:exportToImage();">
</body>

On server side here is the servlet code:

private void doPost(HttpServletRequest request,
        HttpServletResponse response)  throws ServletException, IOException {
    // TODO Auto-generated method stub

    String filePath = "C:/Users/nandan.jain/Pictures/out.jpg";
    File file = new File(filePath);
    int length   = 0;
    ServletOutputStream outStream = response.getOutputStream();

    response.setContentType("image/jpeg");
    response.setContentLength((int)file.length());
    String fileName = (new File(filePath)).getName();

    // sets HTTP header
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

    byte[] byteBuffer = new byte[BUFSIZE];
    DataInputStream in = new DataInputStream(new FileInputStream(file));

    // reads the file's bytes and writes them to the response stream
    while ((in != null) && ((length = in.read(byteBuffer)) != -1))
    {
        outStream.write(byteBuffer,0,length);
    }

    in.close();
    outStream.close();


}

Thanks

Upvotes: 0

Views: 4882

Answers (1)

BalusC
BalusC

Reputation: 1108692

You can't download files with ajax. Ajax is executed by JavaScript language. The JavaScript language has for obvious security reasons no facilities to programmatically trigger a Save As dialog and provide arbitrary file content.

Just download it by a non-ajax request. If Content-Disposition header is set to attachment, the current page will remain unchanged anyway.

So, instead of that whole jQuery.ajax() thing, you could just do

window.location = "convertToImg?q=" + encodeURIComponent(svg1);

and perform the job in servlet's doGet() instead.

Or, if you really need POST, then make it a normal submit form.

<form action="convertToImg" method="post">
    <input type="hidden" name="svg1" />
    <input type="submit" onclick="exportToImage(this)" />
</form>

with

function exportToImage(button) {
    var svg = document.getElementById("ext-gen1040");       
    var svg1 = new XMLSerializer().serializeToString(svg);
    button.form.svg1.value = svg1;
}

Please note that the concrete problem is completely unrelated to JSP/Servlets.

Upvotes: 3

Related Questions