Download file with ajax() POST request via Spring MVC

后端 未结 5 737
予麋鹿
予麋鹿 2020-12-06 11:24

I try to download a file. The action is triggered by ajax() POST request. The request sends data in JSON format to the controller. The controller gener

5条回答
  •  醉酒成梦
    2020-12-06 12:05

    Just send a URL of file in response and then "visit" it in your success callback.

    function getLicenseFile() {
        $.ajax({
            type: 'POST',
            url: '<%=request.getContextPath()%>/licenses/rest/downloadLicenseFile',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            data: ko.mapping.toJSON(licenseModel),
            success: function (data) {
                window.open(data.fileUrl);
                // or window.location.href = data.fileUrl;
            },
            error:function (xhr, ajaxOptions, thrownError) {
                console.log("in error");
            } 
        });
    }
    

    data.fileUrl should be set in response by server to say client where to get the file.

    So your server will send a response with JSON like

    {
        "fileUrl": "http://mysite.com/files/0123456789"
    }
    

提交回复
热议问题