下载文件的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@GetMapping("/download")
public void download(String fid, HttpServletResponse response) throws Exception {
    if (StringUtils.isBlank(fid)) {
        throw new AIPGException("文件ID为空");
    }
    long id = Long.parseLong(fid);
    FileInfo fileInfo = fileOperationService.getFileInfo(id);
    if (fileInfo == null) {
        throw new Exception("该文件不存在");
    }
    String fileName = fileInfo.getFileName();
    byte[] data = fileOperationService.download(id);
    response.setContentType("application/octet-stream");//告诉浏览器输出内容为流
    fileName = new String(fileName.getBytes(), "utf-8");
    response.setHeader("Content-disposition", "attachment;filename=" + fileName);
    try (OutputStream os = response.getOutputStream()) {
        os.write(data);
        os.flush();
    }
}

  前台JS代码

 if (layEvent === 'down') {
                location.href = BASE_CONTEXT_PATH + '/file/download.dsr?fid=' + data.FILE_ID;

通过这种方法可以实现对文件的下载功能。

posted @   jourage  阅读(405)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示