使用MultipartFile實現(xiàn)文件上傳功能
前言
MultipartFile是spring類型,代表HTML中form data方式上傳的文件,包含二進制數(shù)據(jù)+文件名稱。
在文件上傳這方面能幫助我們快速簡潔實現(xiàn)。
使用
1、yml配置文件
spring:
servlet:
multipart:
max-file-size: 10MB #單個最大文件大小,默認是1MB
max-request-size: 100MB #總請求文件大小
2、API介紹
multipartFile.getContentType()//在控制臺打印文件的類型
multipartFile.getName()//返回文件的名稱
multipartFile.getOriginalFilename()//返回文件的原文件名
multipartFile.getSize() //單位為字節(jié)
multipartFile.getInputStream() //文件轉(zhuǎn)換為輸入流
multipartFile.transferTo(new File("D:/"));
/*上傳的文件需要保存的路徑和文件名稱,
本質(zhì)上還是使用了流,只不過是封裝了步驟,相當于:
File file = new File("D:/");
file.createNewFile();
FileOutputStream stream = new FileOutputStream(file);
stream.write(multipartFile.getBytes());
stream.close();
*/
3、文件上傳示例
@RestController
@Slf4j
public class UploadTest {
@RequestMapping("/upload")
public String upLoad(@RequestPart("file") MultipartFile multipartFile){
log.info("文件上傳開始");
log.info("文件{}",multipartFile.getOriginalFilename());
if (!multipartFile.isEmpty()){
try {
//上傳的文件需要保存的路徑和文件名稱,路徑需要存在,否則報錯
multipartFile.transferTo(new File("D:/"++multipartFile.getOriginalFilename()));
} catch (IllegalStateException | IOException e){
e.printStackTrace();
return "上傳失敗";
}
} else {
return "請上傳文件";
}
return "上傳成功";
}
}
注意:
@RequestPart("file")主要用來處理content-type為 multipart/form-data 或 multipart/mixed stream 發(fā)起的請求,可以獲取請求中的參數(shù)。
因此在此處,前端上傳文件時,key為file,value為文件。
4、postman測試
由于本人只會后端不會做前端,懶得查資料寫前端上傳文件功能,就使用postman進行測試。
1、將請求方式改為post。
2、Headers中設置設置key=Content-Type,value=multipart/form-data(默認已設置)。

3、在Body中選擇form-data,選擇File格式,KEY填寫在后端代碼中編寫的@RequestPart(“file”)中的file,value選擇你想要上傳的文件。

4、點擊send即可實現(xiàn)上傳功能。
文件下載
既然文件上傳功能有了,就在此介紹一下如何實現(xiàn)文件下載功能。
@RestController
public class DownTest {
@RequestMapping("/download")
public ResponseEntity<Object> download() throws IOException {
//提供下載的文件的路徑
FileSystemResource file = new FileSystemResource("D:\\cloud/pom.xml");
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
//這里定制下載文件的名稱
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))//以二進制流的形式返回
.body(new InputStreamResource(file.getInputStream()));
}
}
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot采用Dynamic-Datasource方式實現(xiàn)多JDBC數(shù)據(jù)源
在某些情況下,如果我們需要配置多個數(shù)據(jù)源,本文主要介紹了SpringBoot采用Dynamic-Datasource方式實現(xiàn)多JDBC數(shù)據(jù)源,具有一定的參考價值,感興趣的可以了解一下2023-10-10

