文件服务器2?

来源:16-6 登录token超时优化

慕神4535282

2020-11-03

老师,下午好,请教一个问题,
我之前曾向你提过一个文件服务器的问题,参见
https://coding.imooc.com/learn/questiondetail/209905.html

同时,
下面的这段代码也可以实现同样的功能

@GetMapping("download")
public void download(String openStyle, String id, HttpServletResponse response) throws IOException {
    //获取打开方式
    openStyle = openStyle == null ? "attachment" : openStyle;
    //获取文件信息
    UserFile userFile = userFileService.findById(id);
    //点击下载链接更新下载次数
    if ("attachment".equals(openStyle)) {
        userFile.setDowncounts(userFile.getDowncounts() + 1);
        userFileService.update(userFile);
    }
    //根据文件信息中文件名字 和 文件存储路径获取文件输入流
    String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
    //获取文件输入流
    FileInputStream is = new FileInputStream(new File(realpath, userFile.getNewFileName()));
    //附件下载
    response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(userFile.getOldFileName(), "UTF-8"));
    //获取响应输出流
    ServletOutputStream os = response.getOutputStream();
    //文件拷贝
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
} // 摘取自 https://zhuanlan.zhihu.com/p/135383757

我想问的是,什么情况下应该采用你的方式,而什么情况又应该采用上述代码的方式 来对外提取文件下载服务呢?谢谢老师解答!

写回答

1回答

甲蛙

2020-11-04

两者有区别。

你这段是下载文件,从服务器下载到电脑上某个文件夹里

我配置的是静态文件访问,不是下载,比如显示某个图片,加载某个js等,并不会下载到某个文件夹,而是浏览器自己下载后把静态文件渲染出来。

0
1
慕神4535282
非常感谢!
2020-11-04
共1条回复

Spring Cloud+ Vue前后端分离开发企业级在线视频系统

全网稀缺课程 市场热门项目+主流框架 一课掌握前后端技术

1743 学习 · 1698 问题

查看课程