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 export(new FIle());//這裏返回調用export的結果
}

上傳

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, "請求成功!");
    }
});

參考鏈接:

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※專營大陸空運台灣貨物推薦

台灣空運大陸一條龍服務

※評比彰化搬家公司費用,南投搬家公司費用收費行情懶人包大公開

彰化搬家費用,南投搬家費用,距離,噸數怎麼算?達人教你簡易估價知識!