1. 程式人生 > >Spring框架學習筆記(7)——Spring Boot 實現上傳和下載

Spring框架學習筆記(7)——Spring Boot 實現上傳和下載

最近忙著都沒時間寫部落格了,做了個專案,實現了下載功能,沒用到上傳,寫這篇文章也是順便參考學習瞭如何實現上傳,上傳和下載做一篇筆記吧

下載

主要有下面的兩種方式:

  • 通過ResponseEntity實現
  • 通過寫HttpServletResponse的OutputStream實現

我只測試了ResponseEntity<InputStreamResource>這種方法可行,另外一種方法請各位搜尋資料。

我們在controller層中,讓某個方法返回ResponseEntity,之後,使用者開啟這個url,就會直接開始下載檔案

這裡,封裝了一個方法export,負責把File物件轉為ResponseEntity

public ResponseEntity<FileSystemResource> export(File file) {
    if (file == null) {
        return null;
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");//以時間命名檔案,防止出現檔案存在的情況,根據實際情況修改,我這裡是返回一個xls檔案
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    headers.add("Last-Modified", new Date().toString());
    headers.add("ETag", String.valueOf(System.currentTimeMillis()));

    return ResponseEntity
            .ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(new FileSystemResource(file));
}

Controller

@RequestMapping("download")
public ResponseEntity<FileSystemResource> downloadFile() {
    return excelFileService.getGroupExcel(matchId);
}

上傳

1.配置

spring boot使用上傳功能,得先進行配置,spring boot配置方式有兩種,一種是資原始檔properties配置,另外一種方式則是yml配置

properties配置:

## MULTIPART (MultipartProperties)
# 開啟 multipart 上傳功能
spring.servlet.multipart.enabled=true
# 檔案寫入磁碟的閾值
spring.servlet.multipart.file-size-threshold=2KB
# 最大檔案大小
spring.servlet.multipart.max-file-size=200MB
# 最大請求大小
spring.servlet.multipart.max-request-size=215MB

yml配置:

spring:
    servlet:
        multipart:
          enabled: true # 開啟 multipart 上傳功能
          max-file-size: 200MB # 最大檔案大小
          max-request-size: 215MB # 最大檔案請求大小
          file-size-threshold: 2KB # 檔案寫入磁碟的閾值

2.編寫url請求

controller

@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
        return "上傳失敗,請選擇檔案";
    }

    String fileName = file.getOriginalFilename();
    String filePath = "/Users/itinypocket/workspace/temp/";//檔案上傳到伺服器的路徑,根據實際情況修改
    File dest = new File(filePath + fileName);
    try {
        file.transferTo(dest);
        LOGGER.info("上傳成功");
        return "上傳成功";
    } catch (IOException e) {
        LOGGER.error(e.toString(), e);
    }
    return "上傳失敗!";
}

3.Web頁面上傳檔案

注意,input標籤的name與url的請求引數名相同,上傳只能使用post請求
單個檔案上傳:

<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>

多個檔案上傳:

input標籤加上multiple屬性,即可一次選擇多個檔案

<form method="post"  action="/upload" enctype="multipart/form-data">
    <input type="file" multiple name="file"><br>
    <input type="submit" value="提交">
</form>

4.Android端上傳檔案

使用okhttp上傳檔案

RequestBody filebody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
RequestBody body = new MultipartBody.Builder()
        .addFormDataPart("file", file.getName(), filebody)
        .build();
Request request = new Request.Builder()
        .url("http://192.168.1.106:8080/webapp/fileUploadPage")
        .post(body)
        .build();

Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.e(TAG, "請求失敗:" + e.getMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.e(TAG, "請求成功!");
    }
});

參考連結:
spring boot檔案下載
Spring Boot 檔案上傳與下載
Spring Boot教程(十三):Spring Boot檔案上傳
jsp 實現上傳 菜鳥教