前言
MultipartFile是spring類型,代表HTML中form data方式上傳的文件,包含二進(jìn)制數(shù)據(jù)+文件名稱。在文件上傳這方面能幫助我們快速簡潔實現(xiàn)。
使用
1、yml配置文件
spring:
servlet:
multipart:
max-file-size: 10MB #單個最大文件大小,默認(rèn)是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ì)上還是使用了流,只不過是封裝了步驟,相當(dāng)于:
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進(jìn)行測試。
1、將請求方式改為post。
2、Headers中設(shè)置設(shè)置key=Content-Type,value=multipart/form-data(默認(rèn)已設(shè)置)。
3、在Body中選擇form-data,選擇File格式,KEY填寫在后端代碼中編寫的@RequestPart(“file”)中的file,value選擇你想要上傳的文件。
4、點擊send即可實現(xiàn)上傳功能。文章來源:http://www.zghlxwxcb.cn/news/detail-599006.html
文件下載
既然文件上傳功能有了,就在此介紹一下如何實現(xiàn)文件下載功能。文章來源地址http://www.zghlxwxcb.cn/news/detail-599006.html
@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"))//以二進(jìn)制流的形式返回
.body(new InputStreamResource(file.getInputStream()));
}
}
到了這里,關(guān)于MultipartFile實現(xiàn)文件上傳功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!