springboot上传下载文件
创建controller层
@RestController
public class FileDealController {
/**
上传文件的方法,将文件上传到某个存在的位置
@param file 文件名
*/
@PostMapping("/upload")
public void upload(@RequestParam("file")MultipartFile file)throws Exception{
// 这里由于逻辑较多所以封装了一个util
fileUtil.upload(file);
}
/**
下载文件的方法,将文件从某个存在的位置上下载下来
@param filename 文件名
*/
@GetMapping("/download")
public ResponseEntity download(@RequestParam("filename")String filename) throws Exception{
//指定预下载文件的位置
FileSystemResource file = new FileSystemResource("E:\\Tour\\"+filename);
HttpHeaders httpHeaders = new HttpHeaders();
//指定下载后的文件名等,new String(filename.getBytes("UTF-8"),"ISO8859-1")很重要,不然会下载中文名的时候名字为空
httpHeaders.add("Content-Disposition","attachment; filename="+new String(filename.getBytes("UTF-8"),"ISO8859-1"));
return ResponseEntity.ok()
.headers(httpHeaders)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
}
}
上传使用的util
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class fileUtil {
/**
* @param names 文件下文件名的集合
* @param name 存入的文件名
* @param index 索引的开始位置
* @return 符合要求的文件名
*/
private static String checkFileName(ArrayList<String> names, String name, int index) {
String indexName;
if (index == 0 ) {
indexName = name;
} else {
indexName = name.substring(0, name.indexOf(".")) + "(" + index + ")" +name.substring(name.indexOf("."));
}
if (names.contains(indexName)) {
index +=1;
name = checkFileName(names, name, index);
} else {
return indexName;
}
return name;
}
/**
* @param path 需要遍历的路径
* @return 路径下文件的名称集合
*/
private static ArrayList<String> getFile(String path) {
// 获得指定文件对象
File file = new File(path);
// 获得该文件夹内的所有文件
File[] array = file.listFiles();
ArrayList<String> list = new ArrayList<>();
if (array != null) {
for (File value : array) {
list.add(value.getName());
}
}
return list;
}
public static void upload(MultipartFile file) throws IOException {
//上传路径
String uploadPath = "E:\\Tour\\";
ArrayList<String> list = getFile(uploadPath);
/*获取文件名*/
String getFileName = file.getOriginalFilename();
String fileName;
//查询是否重名,重名角标加一
fileName = checkFileName(list, getFileName,0);
String filePath =uploadPath + fileName;
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
outputStream.write(file.getBytes());
outputStream.flush();
outputStream.close();
}
}
测试
测试上传
- 使用postman测试上传
2.去指定路径的文件夹下查看结果
测试下载
在浏览器输入http://localhost:8086/download?filename=nginx-1.18.0.zip进行下载