AngularJS - File Download through AJAX

后端 未结 2 774
遥遥无期
遥遥无期 2021-01-13 15:42

I created an angular js program for downloading a file from the server here follows the code

HTML Code



        
2条回答
  •  猫巷女王i
    2021-01-13 15:59

    I have faced the similar issue for downloading files such as .pdf, .xls, .xlsx etc through Ajax.

    Its a fact that we cant download files through Ajax, even though i came up with a solution which downloads files through Ajax like.

    You can use jquery.fileDownload - A jQuery File Download Plugin for Ajax like, feature rich file downloads.

    Demo Working

    Server Side

    I am using Spring at the server side

    @RequestMapping(value = "exportXLS", method = RequestMethod.POST, produces = APP_JSON)
    @ResponseBody
    public void getCSV(final HttpServletResponse response, @RequestParam(value = "empId", required = true) final String empId) throws IOException, Exception
    {
        final byte[] csv = ExportXLSUtil.getFileBytes(empId); // get the file bytes
        final OutputStream output = getOutputStream(response);
        response.setHeader("Content-Disposition", "attachment; filename=documents_" + new DateTime() + ".xls");
        response.setContentType(CONTENT_TYPE);
        response.setContentLength(csv.length);
        write(output, csv);
    }
    

    Client Side

    At the client side, I am using AngularJS

    $downloadXLS = function(id)
    {
        $.fileDownload('/user/exportXLS', 
        {
            httpMethod : "POST",
            data : {
                empId : id
            }
        }).done(function(e, response)
        {
         // success
        }).fail(function(e, response)
        {
         // failure
        });
    }
    

    Download Link - jquery.fileDownload.js

提交回复
热议问题