下载文件到默认浏览器

紧连着上一条“上传文件”的文章

1、controller层

@RequestMapping(value="/downloadFile")
    @ResponseBody
    public Object downloadFile(@RequestParam(value="docId",required = false)String docId){
            String filePath = "";
            //普通类型文档下载
            DocManager docManager = docManagerService.findDocById(docId);
            if (docManager == null) {
                return MarkUtil.markRetunMsg(false, "未找到文件!");
            }

            filePath = docManager.getDocPath() + docManager.getFileName();
            File file = new File(filePath);
            //下载文件到浏览器
            try {
           		FileSystemResource fileSource = new FileSystemResource(file );
	            return FileUtil.downloadFile(fileSource.getInputStream(),fileSource.getFilename().substring(0,fileSource.getFilename().length()-6)); //保存到数据库的是带随机数的文件名fileName字段,因为将此文件名后面的六位随机数去掉
	        } catch (IOException e) {
	            return MarkUtil.markRetunMsg(false,e.getMessage());
	        }
        }

FileUtil类中的downloadFile方法

/**
 * 下载文件到默认浏览器
 * @param in
 * @param fileName
 * @return
 */
public static ResponseEntity<InputStreamResource> downloadFile(InputStream in,String fileName) {
    try {
        byte[] testBytes = new byte[in.available()];
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", MarkUtil.convertFileName(fileName)));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(testBytes.length)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(in));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

MarkUtil类中的convertFileName方法如下:

/**
 * chinese code convert
 * @param fileName
 * @return
 */
public static String convertFileName(String fileName) {
        if(isContainChinese(fileName)) {
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值