【问题标题】:Save excel file received from the server on client machine在客户端机器上保存从服务器收到的 excel 文件
【发布时间】:2017-04-13 15:24:27
【问题描述】:

我有一个向服务器发送发布请求的链接(“a”元素)。服务器响应一个我想在客户端下载的 excel 文件。

服务器代码:

@RequestMapping(value="/applicabilityExcel", method=POST)
@ResponseBody
public void getApplicability(@RequestParam("id") String reportId, HttpServletResponse response, HttpServletRequest request) throws IOException{
    int id = Integer.valueOf(reportId);
    Report report = repository.getReport(id);
    InputStream is = new ExcelWriter().getConformityMatrix(report);
    response.setContentType("application/vnd.ms-excel");
    org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
    response.flushBuffer();     
}

客户代码:

<a class="appMatrix" href="<c:out value="${report.id}" />"> App</a>
$(".appMatrix").click(function(e) {
    e.preventDefault();
    $.post( "/applicabilityExcel",
            {id:$(this).attr("href")},
            function(data){
                console.log(data);
                //I have the file in data variable and I need now to stock it in the client machine (open dialog window, save it directly...)
            });
});

我的问题是我不知道如何在客户端计算机中存储此文件(“下载它”)。

我尝试将文件下载为 text/base64,将其放在“a”元素的 href 上并调用 click(),但它对我不起作用。

欢迎所有回复和建议。

【问题讨论】:

  • 最简单的方法是将表单发布到相同的 url ...然后会自动强制下载
  • jQuery 在$.ajax() 处理二进制数据时出现问题。 data$.post() 成功回调中是什么?
  • @guest271314 data 是服务器响应 (org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());)。它包含一个excel文件的输入流
  • 您是否尝试过使用XMLHttpRequest() 并将.responseType 设置为"blob",或fetch()Response.blob()
  • @charlietfl,使用表单可以正常工作,但文件名设置为默认文件名。您知道如何设置文件名吗? JavaScript 代码是:$('&lt;input name="id" /&gt;').attr('type', 'hidden') .attr('value',$(this).attr("href")) .appendTo('#formD'); $('#formD').submit();

标签: javascript java jquery html spring-mvc


【解决方案1】:

也许你可以在这里试试这个,对我有用

$scope.exportExcel = function(){
    var self = this;
    var url = //yourapi;
    $http.get(url, { responseType: "arraybuffer" }).then(
        function (result) {
            var blob = new Blob([result.data], { type: 'application/vnd.ms-excel' });
            var a = document.createElement('a');
            var url = URL.createObjectURL(blob);
            a.href = url;
            a.download = ""//yourfilename
            a.target = '_blank';
            document.body.appendChild(a);
            a.click();;
        });
};

【讨论】:

  • 请注意,某些旧版浏览器不支持download
  • 感谢您的回答,但我发现使用@charlietfl 评论中提出的表单帖子是他提到的最简单的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-30
相关资源
最近更新 更多