本文介绍了通过Spring MVC使用ajax()POST请求下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试下载文件。该操作由ajax()发布请求触发。请求以json格式将数据发送到控制器。控制器生成文件(字节)并将其发回。

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 generate the file (bytes) and send it back.

java脚本:

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) {
            console.log("in sucess")
        },
        error:function (xhr, ajaxOptions, thrownError){
            console.log("in error")
        }
    });
}

控制器:

@RequestMapping(value = "/licenses/rest/downloadLicenseFile", method = RequestMethod.POST)
    @ResponseStatus(value=HttpStatus.OK)
    @ResponseBody
    public void createLicenseFile(@Valid @RequestBody License license, HttpServletResponse response) throws Exception {

        logger.debug("Contoller License in: "+ license);

        byte[] licensedata = licenseEncodeDefaultService.createLicenseFile(license);
        logger.debug("licenseData: " + new String(licensedata));

        response.setHeader("Content-Disposition", "attachment; filename=\"" + license.getCustomer() + ".license\"");
        response.getOutputStream().write(licensedata);
        response.flushBuffer();
    }

问题:

*浏览器应该打开一个下载框,但它不会发生 -
*响应是在错误处理的:ajax函数部分(但http状态正常)

Problem:
* The Browser should open a download box, but it will not happed
* The response is handled in the error: section of ajax function (but the http Status is OK)

那么我错了什么或者这样做的正确方法是什么?

So what do I wrong or what is the proper way to do this?

推荐答案

只需发送一个文件的URL作为回应,然后在 success 回调中访问它。

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 应该由服务器设置响应来说明客户端在哪里获取文件。

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

所以你的服务器将发送一个带有JSON的响应,如

So your server will send a response with JSON like

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

这篇关于通过Spring MVC使用ajax()POST请求下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:54