1. 前言
本文的目的是:使用一个简单的上传下载Demo案例,将整理的知识进行总结。其中配有源码/ 图片/ 案例等
2. 源码地址
3. 实现效果
4. 核心原理
4.1 设备
- 两台tomcat服务器,一台服务器作为文件服务器,一台服务器作为项目服务器
4.2 核心依赖介绍
- 解析返回json对象的依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
- 远程服务器上传文件的依赖
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
</dependency>
- 识别请求中 参数是file的依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
4.3 核心代码介绍
@RequestMapping(method = RequestMethod.POST, value = "/uploadFile")
public Map<String, Object> uploadFile(MultipartFile file) throws IOException {
HashMap<String, Object> hashMap = new HashMap<>();
// 文件名称
String originalFilename = file.getOriginalFilename();
// 表示获取扩展名
String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
// 避免文件名称冲突 使用uuid
String uuid = UUID.randomUUID() + "_" + Utils.getCurrentDate();
String newFileName = uuid.concat(suffix);
// 创建 sun公司提供的jersey包中的client对象
Client client = Client.create();
WebResource webResource = client.resource(SERVER_ADDR + newFileName);
// 将文件存储到另一个服务器上去
webResource.put(String.class, file.getBytes());
// 上传成功后 返回对应的状态
hashMap.put("code", "200");
HashMap<String, String> data = new HashMap<>();
data.put("path", SERVER_ADDR);
data.put("filename", newFileName);
data.put("type", file.getContentType());
hashMap.put("data", data);
return hashMap;
}
- 上述的代码核心之处还是利用依赖,进行远程文件上传
@GetMapping(value = "/downloadFile")
public void downloadFile(String filename, String fileType, HttpServletResponse resp) throws IOException {
// 1. 设置响应头
resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
// 2. 设置响应类型
resp.setContentType(fileType);
// 3. 获取一个文件的输入流
InputStream inputStream = new URL(SERVER_ADDR + filename).openStream();
// 4. 设置一个输出流
ServletOutputStream outputStream = resp.getOutputStream();
// 5. 向浏览器响应文件即可
IOUtils.copy(inputStream, outputStream);
}
5. 结束
其实上述的代码比较简单,而且注释中写的很明白了。所以就不多做解释了。如果觉得代码对您有帮助的话,可以直接看源码。 同时也是非常欢迎评论下进行留言以及交流。