Handle file download from ajax post

前端 未结 20 2653
心在旅途
心在旅途 2020-11-21 05:46

I have a javascript app that sends ajax POST requests to a certain URL. Response might be a JSON string or it might be a file (as an attachment). I can easily detect Content

20条回答
  •  野性不改
    2020-11-21 06:14

    Here is my solution, gathered from different sources: Server side implementation :

        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        // Set headers
        response.setHeader("content-disposition", "attachment; filename =" + fileName);
        response.setContentType(contentType);
        // Copy file to output stream
        ServletOutputStream servletOutputStream = response.getOutputStream();
        try (InputStream inputStream = new FileInputStream(file)) {
            IOUtils.copy(inputStream, servletOutputStream);
        } finally {
            servletOutputStream.flush();
            Utils.closeQuitely(servletOutputStream);
            fileToDownload = null;
        }
    

    Client side implementation (using jquery):

    $.ajax({
    type: 'POST',
    contentType: 'application/json',
        url: ,
        data: JSON.stringify(postObject),
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        },
        success: function(message, textStatus, response) {
           var header = response.getResponseHeader('Content-Disposition');
           var fileName = header.split("=")[1];
           var blob = new Blob([message]);
           var link = document.createElement('a');
           link.href = window.URL.createObjectURL(blob);
           link.download = fileName;
           link.click();
        }
    });   
    

提交回复
热议问题