Java实现文件下载、预览

实现文件下载、预览

指定返回前端-文件的格式

PDF文件下载:
HttpServletResponse response
                        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
                        response.setContentType("application/force-download");
PDF文件预览:
HttpServletResponse response
                        response.setHeader("Content-Disposition","inline; filename="+ URLEncoder.encode(fileName,"UTF-8"));
                        response.setContentType("application/pdf");
                        //不写response.setContentType("application/pdf"); 返回给前端的就是一个文件流,window.open(url)打开的就是乱码,指定contentType之后,URL跳转显示的就是pdf的预览文件
上代码:(前端只需window.open(url)即可)
@CrossOrigin
@ApiOperation(value = API_DESC_PREFIX + "文件下载、预览")
@GetMapping(Constants.REFUND_DOWNLOAD)
public void download(
                     @ApiParam(value="refundId")@RequestParam("refundId") String refundId,
                     @ApiParam(required = true,value="类型:1:下载 2:预览")@RequestParam("fileType") String fileType,
                     HttpServletRequest request, HttpServletResponse response){
    HttpHeaders headers = new HttpHeaders();
    OutputStream out = null;
    String fileName="";
    String filePath="";
    try {
        if(StringUtils.isEmpty(refundId)){
            return;
        }
        if(!StringUtils.isEmpty(refundId)){
            // 根据退费id获取文件
            RefundApply refundApply = refundApplyService.refundFindById(refundId);
            if(refundApply!=null){
                filePath=fileServerUrl+refundApply.getFilePath();
                fileName=refundApply.getFileName();
            }
        }
        if(StringUtils.isEmpty(filePath)){
            return;
        }
        ResponseEntity<byte[]> entity = restTemplate.exchange(filePath, HttpMethod.GET,new HttpEntity<>(headers), byte[].class);
        if (entity.getStatusCodeValue()==200) {
            byte[] bytes =  entity.getBody();
            //fileType:1:下载、2:预览
            switch (fileType) {
                case "1":
                    response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
                    response.setContentType("application/force-download");
                    break;
                case "2":
                    response.setHeader("Content-Disposition","inline; filename="+ URLEncoder.encode(fileName,"UTF-8"));
                    response.setContentType("application/pdf");
                    break;
                default:
                    break;
            }
            out = response.getOutputStream();
            out.write(bytes);
            out.flush();
        }else {
            response.setStatus(500);
        }
    } catch (Exception e) {
        log.error(String.format("文件下载报错:%s",e.getMessage()) ,e);
        response.setStatus(500);
    }finally {
        if (out != null){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

返回前端是个流(未指定文件格式)

上代码(前端需要借助组件对流进行分析,例如图片的流借助 img标签的 src请求url即可)
@CrossOrigin
@ApiOperation(value = API_DESC_PREFIX + "图片预览")
@GetMapping(Constants.SPECIAL_WATCH)
public void specialWatch(
        @ApiParam(value="path")@RequestParam(value = "path",required = true) String path,
        @ApiParam(value="name")@RequestParam(value = "name",required = true) String name,
        HttpServletRequest request, HttpServletResponse response){
    HttpHeaders headers = new HttpHeaders();
    OutputStream out = null;
    String filePath="";
    try {
        if((!StringUtils.isEmpty(path)) && (!StringUtils.isEmpty(name))){
            filePath=fileServerUrl+path;
        }else {
            return;
        }
        ResponseEntity<byte[]> entity = restTemplate.exchange(filePath, HttpMethod.GET,new HttpEntity<>(headers), byte[].class);
        if (entity.getStatusCodeValue()==200) {
            byte[] bytes =  entity.getBody();
            response.setHeader("Content-Disposition","inline; filename="+ URLEncoder.encode(name,"UTF-8"));
            out = response.getOutputStream();
            out.write(bytes);
            out.flush();
        }else {
            response.setStatus(500);
        }
    } catch (Exception e) {
        log.error(String.format("图片预览报错:%s",e.getMessage()) ,e);
        response.setStatus(500);
    }finally {
        if (out != null){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值