扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

springboot涓婁紶涓嬭浇鍔熻兘鎬庝箞瀹炵幇

扬州沐宇科技
2023-11-06 22:42:06
springboot

鍦⊿pring Boot涓紝鍙互浣跨敤MultipartFile鎺ュ彛鏉ュ疄鐜版枃浠朵笂浼犲姛鑳斤紝浣跨敤ResponseEntity鏉ュ疄鐜版枃浠朵笅杞藉姛鑳姐€?/p>

鏂囦欢涓婁紶鍔熻兘鐨勫疄鐜版楠ゅ涓嬶細

  1. 鍦–ontroller涓坊鍔犱竴涓鐞嗘枃浠朵笂浼犵殑鏂规硶锛屽苟浣跨敤@RequestParam娉ㄨВ鏉ユ帴鏀朵笂浼犵殑鏂囦欢鍙傛暟銆?/li>
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
    // 澶勭悊鏂囦欢涓婁紶閫昏緫
    // ...
    return "涓婁紶鎴愬姛";
}
  1. 鍦╝pplication.properties鎴朼pplication.yml閰嶇疆鏂囦欢涓坊鍔犳枃浠朵笂浼犵浉鍏崇殑閰嶇疆銆?/li>
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  1. 鍦ㄥ墠绔〉闈腑娣诲姞涓€涓枃浠朵笂浼犺〃鍗曪紝骞惰缃甧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>

鏂囦欢涓嬭浇鍔熻兘鐨勫疄鐜版楠ゅ涓嬶細

  1. 鍦–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);
}
  1. 鍦ㄥ墠绔〉闈腑娣诲姞涓€涓笅杞芥寜閽紝骞惰缃搴旂殑涓嬭浇閾炬帴銆?/li>
<a th:href="@{/download/filename}" download>涓嬭浇</a>

鍏朵腑锛宖ilename涓鸿涓嬭浇鐨勬枃浠跺悕銆?/p>

浠ヤ笂灏辨槸Spring Boot涓疄鐜版枃浠朵笂浼犱笅杞藉姛鑳界殑鍩烘湰姝ラ銆傚叿浣撳疄鐜版牴鎹叿浣撻渶姹傚彲鑳戒細鏈夋墍涓嶅悓锛屽彲浠ユ牴鎹渶瑕佽繘琛岃皟鏁淬€?/p>

扫码添加客服微信