有啥不懂的或者出錯(cuò)的可以在下面留言蒲讯。
1. 文件上傳
//上傳路徑
String folder = "C:\\code\\springboot-springsecurity\\security-demo\\src\\main\\java\\com\\laojiao\\xxx\\controller";
@PostMapping
public String upload(MultipartFile file) throws IOException {
System.out.println(file.getName());
System.out.println(file.getOriginalFilename());
System.out.println(file.getSize());
//創(chuàng)建本地文件
File localFile = new File(folder,System.currentTimeMillis()+".txt");
//把傳上來(lái)的文件寫到本地文件
file.transferTo(localFile);
//返回localFile文件路徑
return localFile.getAbsolutePath();
}
返回是String就是文件所在路徑宰掉,一般把它放到數(shù)據(jù)庫(kù)中蕴侧。
我在這里用的是單機(jī)上傳择同,如果有需要上傳到ftp或者fastdfs等文件服務(wù)器,請(qǐng)看下面核心代碼净宵。
//利用 MultipartFile 的 transferTo 方法 上傳文件 至 path
file.transferTo(targetFile);
//上傳到 FTP 服務(wù)器
FTPUtil.uploadFile(Lists.newArrayList(targetFile));
//刪除 path 路徑下的 文件
targetFile.delete();
最后返回一個(gè)文件名敲才。需要下載或者獲取文件的時(shí)候裹纳,給該文件名加上前綴即可。
2. 文件下載
@GetMapping("/{id}")
public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response){
try(InputStream inputStream = new FileInputStream(new File(folder,id+".txt"));
OutputStream outputStream = response.getOutputStream();) {
//設(shè)置內(nèi)容類型為下載類型
response.setContentType("application/x-download");
//設(shè)置請(qǐng)求頭 和 文件下載名稱
response.addHeader("Content-Disposition","attachment;filename=test.txt");
//用 common-io 工具 將輸入流拷貝到輸出流
IOUtils.copy(inputStream,outputStream);
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
注意IOUtils 是apache的一個(gè)工具包归斤,是需要導(dǎo)入common-io
依賴包的痊夭。或者你手動(dòng)獲取輸入輸出流轉(zhuǎn)換也可以脏里。
介紹下我的所有文集:
流行框架
SpringCloud
springboot
nginx
redis
底層實(shí)現(xiàn)原理:
Java NIO教程
Java reflection 反射詳解
Java并發(fā)學(xué)習(xí)筆錄
Java Servlet教程
jdbc組件詳解
Java NIO教程
Java語(yǔ)言/版本 研究