angularjs 和jersey 实现文件下载

3 篇文章 0 订阅
1 篇文章 0 订阅
$http({
method : "post",
url : Constant.prefixUrl+"/customerQueryCount/exportMonthReport",
timeout : Constant.timeout,
responseType: "blob"   //注意此参数
}).success(function(data, status, headers, config){
var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});  
if(blob.size>0){
var fileName = $rootScope.currentAdminUserId +""+ (new Date()).getTime();
var a = document.createElement("a");
document.body.appendChild(a);
a.download = fileName;
a.href = URL.createObjectURL(blob);
a.click();
}else{
deferred.resolve("下载报表失败");
}
}).error(function(data, status, headers, config){
commonService.goLoginPage(status);

});

后台:

    @POST
    @Path("/export2")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public byte[] export2(@RequestBody String params, @Context HttpServletResponse response) {

        File file = new File(filePath + filePrefix + ".xlsx");

        FileInputStream fis;
        byte[] b =    null;
        try {
            fis = new FileInputStream(file);
            b = new byte[fis.available()];
            fis.read(b);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        response.setHeader("Content-Disposition", "attachment;filename=" + fu + ".xlsx" );// 为文件命名
        response.addHeader("content-type", "application/pdf");
        return b;



Jersey实现文件下载有两种方式。一种是直接将文件作为响应体,另一种是使用StreamingOutput对象作为响应体。第一种方式是通过使用文件对象作为响应体来实现下载功能。在这种方式下,需要判断文件对象是否存在,如果不存在则返回404错误。然后使用文件的路径创建一个文件对象,并将其作为响应体返回。同时,还需要设置响应头部的Content-disposition属性来指定文件的名称和下载方式。第二种方式是使用StreamingOutput对象作为响应体来实现下载功能。这种方式适用于一些没有源文件,直接输出流内容的场景,如内存中构造的图片、Excel文件或PDF文件。在这种方式下,首先判断文件是否存在,如果不存在则返回404错误。然后创建一个StreamingOutput对象,并在其write方法中将文件内容写入输出流。最后,设置响应头部的Content-disposition属性来指定文件的名称和下载方式。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Jersey 文件下载](https://blog.csdn.net/qq_28334711/article/details/54910161)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [jersey中的文件下载](https://blog.csdn.net/LJX_ahut/article/details/89161321)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值