springboot涓婁紶涓嬭浇鍔熻兘鎬庝箞瀹炵幇
鍦⊿pring Boot涓紝鍙互浣跨敤MultipartFile鎺ュ彛鏉ュ疄鐜版枃浠朵笂浼犲姛鑳斤紝浣跨敤ResponseEntity鏉ュ疄鐜版枃浠朵笅杞藉姛鑳姐€?/p>
鏂囦欢涓婁紶鍔熻兘鐨勫疄鐜版楠ゅ涓嬶細
- 鍦–ontroller涓坊鍔犱竴涓鐞嗘枃浠朵笂浼犵殑鏂规硶锛屽苟浣跨敤@RequestParam娉ㄨВ鏉ユ帴鏀朵笂浼犵殑鏂囦欢鍙傛暟銆?/li>
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// 澶勭悊鏂囦欢涓婁紶閫昏緫
// ...
return "涓婁紶鎴愬姛";
}
- 鍦╝pplication.properties鎴朼pplication.yml閰嶇疆鏂囦欢涓坊鍔犳枃浠朵笂浼犵浉鍏崇殑閰嶇疆銆?/li>
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
- 鍦ㄥ墠绔〉闈腑娣诲姞涓€涓枃浠朵笂浼犺〃鍗曪紝骞惰缃甧nctype灞炴€т负multipart/form-data銆?/li>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">涓婁紶</button>
</form>
鏂囦欢涓嬭浇鍔熻兘鐨勫疄鐜版楠ゅ涓嬶細
- 鍦–ontroller涓坊鍔犱竴涓鐞嗘枃浠朵笅杞界殑鏂规硶锛屽苟浣跨敤PathVariable娉ㄨВ鏉ユ帴鏀舵枃浠跺悕鍙傛暟銆?/li>
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
// 鑾峰彇鏂囦欢璺緞
String filePath = "path/to/file/" + filename;
// 鍒涘缓鏂囦欢璧勬簮瀵硅薄
Resource fileResource = new FileSystemResource(filePath);
// 璁剧疆鍝嶅簲澶?/span>
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
return ResponseEntity.ok()
.headers(headers)
.contentLength(fileResource.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(fileResource);
}
- 鍦ㄥ墠绔〉闈腑娣诲姞涓€涓笅杞芥寜閽紝骞惰缃搴旂殑涓嬭浇閾炬帴銆?/li>
<a th:href="@{/download/filename}" download>涓嬭浇</a>
鍏朵腑锛宖ilename涓鸿涓嬭浇鐨勬枃浠跺悕銆?/p>
浠ヤ笂灏辨槸Spring Boot涓疄鐜版枃浠朵笂浼犱笅杞藉姛鑳界殑鍩烘湰姝ラ銆傚叿浣撳疄鐜版牴鎹叿浣撻渶姹傚彲鑳戒細鏈夋墍涓嶅悓锛屽彲浠ユ牴鎹渶瑕佽繘琛岃皟鏁淬€?/p>
相关问答