- ?简单配置
- ?
- 上传
-
/**
* 配置文件中的路径
*/
@Value("${file.path}")
private String path;
@PostMapping(value = "upload")
public String upload(MultipartFile file) {
try {
if (!file.isEmpty()) {
String originalFilename = file.getOriginalFilename();
String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + originalFilename;
File file1 = new File(path + fileName);
file.transferTo(file1);
}
} catch (Exception e) {
e.printStackTrace();
}
return "上传成功!";
} - 测试?
- 结果
- 下载
-
@PostMapping("download")
public void download(String fileName, HttpServletResponse response) {
//文件路径自行修改
File file = new File("E://path/" + fileName);
if (file.exists()) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
response.setCharacterEncoding("UTF-8");
// 如果文件名为中文需要设置编码
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf8"));
int len = 0;
while ((len = fileInputStream.read()) != -1) {
outputStream.write(len);
}
outputStream.flush();
fileInputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
?
|