springboot文件上傳下載(fastdfs,七牛雲,本地)

springboot文件上傳下載(fastdfs,七牛雲,內部外部磁盤{本地})

在實際開發中 ,基本都會有應用到文件上傳的場景,但隨着或多或少的需求問題 ,所採用的技術方案也不盡相同 ,有用 fastdfs 文件存儲服務器的,有用七牛雲的,有直接就將文件傳到自己部署的服務器上的(win 開發存放某一盤符,linux 存放某一路徑下)

本文主要是使用springboot 整合文件上傳就一共分爲了此三個大模塊


(一)springboot-fastdfs

此文章之前以作爲了獨立博客進行發佈 點擊springoot-fastdfs文件存儲服務器實現文件上傳下載 可直連跳轉


(二)springboot整合七牛雲 存儲

(1)七牛雲開通與創建存儲空間

要使用七牛雲 ,首先我們需要進行註冊以及開通儲存空間

七牛雲 這是七牛雲的官方網站 未有賬號的需進行先註冊 註冊過後再按照提示進行實名認證,咱們就有免費10G 的存儲空間了。
注意的是 認證的時候 有一欄要填寫個人網站 ,如果沒有 可以不填 ,只要自己身份信息正確也能通過認證(這一點 七牛提示性不夠啊)

註冊實名後呢
首先查看自己的密鑰信息
ak sk 使我們項目中使用代碼操作七牛 必須要使用的密鑰 切記不要泄露以及隨意傳播
在這裏插入圖片描述
然後開通儲存空間
在這裏插入圖片描述
點擊新建空間 設置空間名 選擇空間所在地區
在這裏插入圖片描述
看情況選擇公開是還私有,至於兩者區別 七牛也說的很詳細了 僅僅是 是否可讀而已 (查看)
在這裏插入圖片描述
我這裏選擇的是華南地區的空間哈 創好了就會在七牛空間列表展示了
在這裏插入圖片描述
進入空間中 自己可以選擇是否綁定域名 如果沒綁 七牛會給你此空間 有限時間三十天的一個隨機域名, 通過這個域名+文件名 我們就可以在任何有網絡的地方進行文件訪問了 個人exmaple:http://qa7oc48w0.bkt.clouddn.com/logo.png
在這裏插入圖片描述

到這一步 我們七牛雲的存儲空間已經開通了 ,接下來咱們就可以再項目中使用了

所需依賴

    <!--java  整合七牛雲 依賴包-->
    <dependency>
      <groupId>com.qiniu</groupId>
      <artifactId>qiniu-java-sdk</artifactId>
      <version>[7.2.0, 7.2.99]</version>
    </dependency>
    <!--七牛需要用到此依賴-->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
    </dependency>
(2)在springboot配置文件中 自定義七牛雲配置
#七牛雲配置
qiniu:
  #自己賬戶的ak sk
  accessKey: xxx
  secretKey: xxx
  #存儲空間名
  bucket: xxx
  # 自己的存儲空間域名
  cdnProfile: xxx
  #採用的協議 http:// 還是 https://  個人此空間由於沒配域名 採用的是http協議  http://qa7oc48w0.bkt.clouddn.com/logo
  protocol: http://
(3)自定義bean 進行 配置解析

個人使用了靜態變量 獲取空間名示例:QiNiuConfigBean.getBucket()

/**
 * @author lei
 * @date 2020/5/12 17:20
 * @desc
 */
@ConfigurationProperties(prefix = "qiniu")
@Component
public class QiNiuConfigBean {

  private static String accessKey;
  private static String secretKey;
  private static String bucket;
  private static String cdnProfile;
  private static String protocol;

  public static String getAccessKey() {
    return accessKey;
  }

  public  void setAccessKey(String accessKey) {
    QiNiuConfigBean.accessKey = accessKey;
  }

  public static String getSecretKey() {
    return secretKey;
  }

  public  void setSecretKey(String secretKey) {
    QiNiuConfigBean.secretKey = secretKey;
  }

  public static String getBucket() {
    return bucket;
  }

  public  void setBucket(String bucket) {
    QiNiuConfigBean.bucket = bucket;
  }

  public static String getCdnProfile() {
    return cdnProfile;
  }

  public  void setCdnProfile(String cdnProfile) {
    QiNiuConfigBean.cdnProfile = cdnProfile;
  }

  public static String getProtocol() {
    return protocol;
  }

  public  void setProtocol(String protocol) {
    QiNiuConfigBean.protocol = protocol;
  }
}
(4)根據配置bean 編寫我們的七牛上傳支持配置

配置類中 包含了 認證信息實例 存儲區域選擇 七牛空間管理實例 上傳工具實例

package com.leilei.config;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author lei
 * @date 2020/5/12 17:32
 * @desc
 */
@Configuration
public class QiNiuConfig {

  /**
   * 配置自己空間所在的區域 我這裏是華南 (個人選擇開通的存儲區域)
   */
  @Bean
  public com.qiniu.storage.Configuration qiniuConfig() {
    return new com.qiniu.storage.Configuration(Zone.huanan());
  }

  /**
   * 構建一個七牛上傳工具實例
   */
  @Bean
  public UploadManager uploadManager() {
    return new UploadManager(qiniuConfig());
  }

  /**
   * 認證信息實例
   *
   * @return
   */
  @Bean
  public Auth auth() {

    return Auth.create(QiNiuConfigBean.getAccessKey(), QiNiuConfigBean.getSecretKey());
  }

  /**
   * 構建七牛空間管理實例
   */
  @Bean
  public BucketManager bucketManager() {
    return new BucketManager(auth(), qiniuConfig());
  }

  @Bean
  public Gson gson() {
    return new Gson();
  }

}
(5)個人參照官方demo示例而修改以及符合個人項目需求的的上傳下載 刪除 工具類

特別注意的 在本工具類中 大量代碼採用了讀取我之前定義的配置bean 如果拷貝我的yml 代碼和自定義bean 即可一鍵使用,直接操作 簡單快捷…

在上傳成功後 會返回一個可直接訪問的Url地址 ,複製到瀏覽器即可查看 或者登陸七牛雲在空間中查看

package com.leilei.util;

import com.leilei.config.QiNiuConfigBean;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.net.URLEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lei
 * @date 2020/5/12 18:03
 * @desc
 */
@Service
@Slf4j
public class QiNiuSupport {

  @Autowired
  private UploadManager uploadManager;

  @Autowired
  private BucketManager bucketManager;

  @Autowired
  private Auth auth;


  /**
   * 最大嘗試次數
   */
  public static final Integer maxReTry = 3;
  /**
   * 七牛雲操作成功狀態碼
   */
  public static final Integer successCode = 200;


  /**
   * 以文件的形式上傳 並設置文件上傳類型
   *
   * @param file
   * @return
   * @throws QiniuException
   */
  public String uploadFileMimeType(File file, String fileName) throws QiniuException {
    //獲取要上傳文件的MIME 類型
    String mime = URLConnection.guessContentTypeFromName(file.getName());
    log.info("當前文件MIME類型爲:{}", mime);
    Response response = this.uploadManager.put(file, fileName, getUploadToken(), getPutPolicy(),
        mime, false);
    int retry = 0;
    while (response.needRetry() && retry < maxReTry) {
      log.info("當前操作需要進行重試,目前重試第{}次",retry+1);
      response = this.uploadManager.put(file, fileName, getUploadToken(), getPutPolicy(),
          mime, false);
      retry++;
    }
    if (response.statusCode == successCode) {
      return new StringBuffer().append(QiNiuConfigBean.getProtocol())
          .append(QiNiuConfigBean.getCdnProfile()).append("/").append(fileName).toString();
    }
    return "上傳失敗!";
  }

  /**
   * 以文件的形式上傳
   *
   * @param file
   * @return
   * @throws QiniuException
   */
  public String uploadFile(File file, String fileName) throws QiniuException {
    Response response = this.uploadManager.put(file, fileName, getUploadToken());
    int retry = 0;
    while (response.needRetry() && retry < maxReTry) {
      log.info("當前操作需要進行重試,目前重試第{}次",retry+1);
      response = this.uploadManager.put(file, fileName, getUploadToken());
      retry++;
    }
    if (response.statusCode == successCode) {
      return new StringBuffer().append(QiNiuConfigBean.getProtocol())
          .append(QiNiuConfigBean.getCdnProfile()).append("/").append(fileName).toString();
    }
    return "上傳失敗!";
  }

  /**
   * 以流的形式上傳
   *
   * @param inputStream
   * @return
   * @throws QiniuException
   */
  public String uploadFileInputStream(InputStream inputStream, String fileName)
      throws QiniuException {
    Response response = this.uploadManager.put(inputStream, fileName, getUploadToken(), null, null);
    int retry = 0;
    while (response.needRetry() && retry < maxReTry) {
      log.info("當前操作需要進行重試,目前重試第{}次",retry+1);
      response = this.uploadManager.put(inputStream, fileName, getUploadToken(), null, null);
      retry++;
    }
    if (response.statusCode == successCode) {
      return new StringBuffer().append(QiNiuConfigBean.getProtocol())
          .append(QiNiuConfigBean.getCdnProfile()).append("/").append(fileName).toString();
    }
    return "上傳失敗!";
  }

  /**
   * 刪除七牛雲上的相關文件
   *
   * @param key
   * @return
   * @throws QiniuException
   */
  public String delete(String key) throws QiniuException {
    Response response = bucketManager.delete(QiNiuConfigBean.getBucket(), key);
    int retry = 0;
    //判斷是否需要 重試 刪除 且重試次數爲3
    while (response.needRetry() && retry++ < maxReTry) {
      log.info("當前操作需要進行重試,目前重試第{}次",retry+1);
      response = bucketManager.delete(QiNiuConfigBean.getBucket(), key);
    }
    return response.statusCode == successCode ? "刪除成功!" : "刪除失敗!";
  }


  /**
   * 獲取上傳憑證
   *
   * @return
   */
  private String getUploadToken() {
    return this.auth.uploadToken(QiNiuConfigBean.getBucket());
  }

  /**
   * 定義七牛雲上傳的相關策略
   */
  public StringMap getPutPolicy() {
    StringMap stringMap = new StringMap();
    stringMap.put("returnBody",
        "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
    return stringMap;
  }

  /**
   * 獲取公共空間文件
   * @param fileKey  要下載的文件名
   * @return
   */
  public String getPublicFile(String fileKey) throws Exception{
    String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
    String url = String.format("%s%s/%s", QiNiuConfigBean.getProtocol(),QiNiuConfigBean.getCdnProfile(), encodedFileName);
    log.info("下載地址:{}", url);
    return url;
  }

  /**
   * 獲取私有空間文件
   * @param fileKey 要下載的文件名
   * @return
   */
  public String getPrivateFile(String fileKey) throws Exception{
    String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
    String publicUrl = String.format("%s/%s", QiNiuConfigBean.getCdnProfile(), encodedFileName);
    //1小時,可以自定義鏈接過期時間
    long expireInSeconds = 3600;
    String privateUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
    return privateUrl;
  }


  /**
   * MultipartFile 轉file
   *
   * @param file
   * @return
   * @throws Exception
   */
  public File multipartFileToFile(MultipartFile file) throws Exception {

    File toFile = null;
    if (file.equals("") || file.getSize() <= 0) {
      file = null;
    } else {
      InputStream ins = null;
      ins = file.getInputStream();
      toFile = new File(file.getOriginalFilename());
      inputStreamToFile(ins, toFile);
      ins.close();
    }
    return toFile;
  }

  //獲取流文件
  private void inputStreamToFile(InputStream ins, File file) {
    try {
      OutputStream os = new FileOutputStream(file);
      int bytesRead = 0;
      byte[] buffer = new byte[8192];
      while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
        os.write(buffer, 0, bytesRead);
      }
      os.close();
      ins.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
(6)七牛雲存儲的簡單使用就搞完了, 接下來咱們編寫接口開始測試

在這裏插入圖片描述
查看七牛上也有了對應的文件
在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述
測試文件刪除
在這裏插入圖片描述
到七牛雲查看 文件已經被刪除了
放上我的全部測試接口

package com.leilei.controller;

import com.leilei.util.QiNiuSupport;
import com.qiniu.common.QiniuException;
import java.io.File;
import java.io.InputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lei
 * @date 2020/5/12 18:05
 * @desc
 */
@RequestMapping("qiniu")
@RestController
public class QiNiuController {

  @Autowired
  private QiNiuSupport qiNiuSupport;

  /**
   * 根據文件名刪除
   * @param name
   * @return
   * @throws QiniuException
   */
  @GetMapping("delete/{name}")
  public String delete(@PathVariable("name") String name) throws QiniuException {
    return qiNiuSupport.delete(name);
  }

  /**
   * 直接傳輸文件 到七牛
   * @param file
   * @return
   * @throws Exception
   */
  @PostMapping("upload")
  public String upload(@RequestParam("file")MultipartFile file) throws Exception {
    return qiNiuSupport.uploadFile(file);
  }

  /**
   * 以流的形式進行上傳
   * @param file
   * @return
   * @throws Exception
   */
  @PostMapping("uploadByStream")
  public String uploadInputStream(@RequestParam("file")MultipartFile file) throws Exception {

    return qiNiuSupport.uploadFileInputStream(file);
  }


  /**
   * 直接傳輸文件 到七牛雲 讀取文件類型 傳輸 MIME 保存
   * @param file
   * @param fileName
   * @return
   * @throws Exception
   */
  @PostMapping("uploadMime/{fileName}")
  public String uploadMIme(@RequestParam("file")MultipartFile file, @PathVariable("fileName") String fileName) throws Exception {
    File file1 = qiNiuSupport.multipartFileToFile(file);
    return qiNiuSupport.uploadFileMimeType(file1, fileName);
  }


  /**
   * 七牛雲文件下載
   *
   * @param filename 文件名
   * @return
   */
  @RequestMapping("/file/{filename}")
  public void download(@PathVariable("filename") String filename, HttpServletResponse response) {
    if (filename.isEmpty()) {
      return;
    }
    try {
      String privateFile = qiNiuSupport.getPublicFile(filename);
      response.sendRedirect(privateFile);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


}

至於文件上傳的時候,是選擇根據文件名自定獲取存儲的名字 還是根據傳入參數來設定 可根據項目需求來定 漢字拼音工具我已補充填入項目中了。

至於爲什麼要漢字轉拼音
在這裏插入圖片描述
如果不轉拼音 文件名與文件鏈接就不一致了 那麼刪除時候 必須根據 存儲的名字 那查看的時候 又是一串轉碼符號鏈接,,,,,,感覺不統一
在這裏插入圖片描述
附上漢字轉拼音
依賴

    <!--漢字轉拼音-->
    <dependency>
      <groupId>com.belerweb</groupId>
      <artifactId>pinyin4j</artifactId>
      <version>2.5.0</version>
    </dependency>
package com.leilei.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author lei
 * @date 2020/5/13 11:02
 * @desc
 */
public class Chines2PingUtils {

  public static String getFirstSpell(String chinese) {
    StringBuffer pybf = new StringBuffer();
    char[] arr = chinese.toCharArray();
    HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

    for (int i = 0; i < arr.length; i++) {
      if (arr[i] > 128) {
        try {
          String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
          if (temp != null) {
            pybf.append(temp[0].charAt(0));
          }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
          e.printStackTrace();
        }
      } else {
        pybf.append(arr[i]);
      }
    }
    return pybf.toString().replaceAll("\\W", "").trim().toUpperCase();
  }

  /**
   * 獲取漢字串拼音,英文字符不變
   *
   * @param chinese
   * @return
   */
  public static String getFullSpell(String chinese) {
    StringBuffer pybf = new StringBuffer();
    char[] arr = chinese.toCharArray();
    HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    for (int i = 0; i < arr.length; i++) {
      if (arr[i] > 128) {
        try {
          pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
        } catch (BadHanyuPinyinOutputFormatCombination e) {
          e.printStackTrace();
        }
      } else {
        pybf.append(arr[i]);
      }
    }
    return pybf.toString();
  }

  public static void main(String[] args) {
    String fullSpell = Chines2PingUtils.getFullSpell("aaaaa.txt");
    System.out.println(fullSpell);
  }
}

到這裏 七牛雲相關操作就結束了 !!由於官網文檔很全面 所以操作起來還是很容易上手 且簡單的。
附上項目源碼:springoot-qiniu


(三)springboot 文件上傳下載 本地

springboot 中 對文件進行上傳下載刪除 基於本地或服務器路徑,不借助第三方工具(win 就放在某盤符中 例如 D://img | Linux 就放在某一路徑下 例如 /webtest/a/c/file/
即通過url 訪問磁盤中的文件

(1)所需依賴

主要是web支持以及 lombok 簡化pojo類

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
(2)添加配置

yml配置

#自定義 file 訪問配置 以及下載上傳地址
file:
  urlPath: /lei
  #上傳路徑 win  D://aa/  linux: /web/c/a/d
  uploadPath: D://aa/

spring:
  # 文件上傳下載配置
  servlet:
    multipart:
      # 單個文件最大限制 10M
      max-file-size:  10MB
      # 上傳總文件總共 100Mb
      max-request-size:  100MB

自定義bean 解析 yml,其他任何需要使用地方統一調用bean進行獲取

需要在啓動類上添加 @EnableConfigurationProperties 註解

/**
 * @author lei
 * @date 2020/5/12 14:18
 * @desc
 */
@ConfigurationProperties(prefix = "file")
@Component
public class FileConfigBean {
  /**圖片上傳後 需加入的訪問前綴*/
  private static String urlPath;
  /**圖片上傳的路徑*/
  private static String uploadPath;

  public static String getUrlPath() {
    return urlPath;
  }

  public  void setUrlPath(String urlPath) {
    FileConfigBean.urlPath = urlPath;
  }

  public static String getUploadPath() {
    return uploadPath;
  }

  public  void setUploadPath(String uploadPath) {
    FileConfigBean.uploadPath = uploadPath;
  }
}

添加圖片訪問資源解析

定義一個類 實現 WebMvcConfigurer 複寫其中的addResourceHandlers 方法

/**
 * @author lei
 * @date 2020/5/12 14:17
 * @desc 添加虛擬映射路徑  以   FileConfigBean.getUrlPath() + "/**" 訪問的靜態資源 都會去  "file:"+ FileConfigBean.getUploadPath() 尋找
 * 若部署在linux 中 需注意更改 FileConfigBean.getUploadPath() 的路徑  linux 上可沒有 CDEFG 盤符  exmaple: file:/home/app/
 */
@Configuration
public class FileConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //可以添加多個   registry.
    registry.addResourceHandler(FileConfigBean.getUrlPath() + "/**")
        .addResourceLocations("file:"+ FileConfigBean.getUploadPath());
  }
}
(3)上傳下載刪除工具類編寫

上傳主要是通過文件上傳地址和傳入的文件 拼接 生成一個file 然後判斷父目錄是否存在 然後寫入即可

上傳時源文件名拼接當前時間戳 作爲名字

至於刪除則也是 傳入相應文件名 然後 拼接上 自定義的file 上傳路徑 判斷是否存在 存在則刪除

package com.leilei.util;

import com.leilei.config.FileConfigBean;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lei
 * @date 2020/5/12 14:49
 * @desc 文件上傳下載工具類
 */
@Slf4j
public class FileUtils {

  /**
   * 上傳單個文件
   *
   * @param file
   * @return
   */
  public static Boolean uploadOne(MultipartFile file) {
    if (file.isEmpty()) {
      return false;
    }
    Long time = System.currentTimeMillis();
    String fileName = time + file.getOriginalFilename();
    int size = (int) file.getSize() / 1024;
    log.info("當前上傳文件名:{},上傳時間戳:{},保存後文件名:{},-->文件大小爲:{}KB", file.getOriginalFilename(), time,
        fileName, size);
    File dest = new File(FileConfigBean.getUploadPath() + "/" + fileName);
    //判斷文件父目錄是否存在 不存在則創建
    if (!dest.getParentFile().exists()) {
      dest.getParentFile().mkdir();
    }
    try {
      file.transferTo(dest);
      return true;
    } catch (IOException e) {
      e.printStackTrace();
      log.error("單文件上傳失敗");
      return false;
    }
  }

  /**
   * 批量上傳  實質就是 單文件上傳 循環版罷了
   *
   * @param files
   * @return
   */
  public static Boolean uploadMore(List<MultipartFile> files) {

    if (files != null && files.size() > 0) {
      for (int i = 0; i < files.size(); i++) {
        MultipartFile file = files.get(i);
        if (!file.isEmpty()) {
          Long time = System.currentTimeMillis();
          String fileName = time + file.getOriginalFilename();
          int size = (int) file.getSize() / 1024;
          log.info("當前上傳文件名:{},上傳時間戳:{},保存後文件名:{},-->文件大小爲:{}KB", file.getOriginalFilename(), time,
              fileName, size);
          File dest = new File(FileConfigBean.getUploadPath() + "/" + fileName);
          //判斷文件父目錄是否存在 不存在則創建
          if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
          }
          try {
            file.transferTo(dest);
            continue;
          } catch (IOException e) {
            e.printStackTrace();
            log.error("第{}個文件上傳失敗", i + 1);
            continue;
          }
        }
      }
      return true;
    }
    return false;
  }

  /**
   * 文件下載
   *
   * @param res
   * @param fileName 要下載的文件名
   * @return
   */
  public static void download(HttpServletResponse res, String fileName) {
    //響應頭設置
    res.setHeader("content-type", "application/octet-stream");
    res.setContentType("application/octet-stream");
    res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    byte[] buff = new byte[1024];
    BufferedInputStream bis = null;
    OutputStream os = null;
    try {
      os = res.getOutputStream();
      bis = new BufferedInputStream(new FileInputStream(new File(FileConfigBean.getUploadPath()
          + fileName)));
      int i = bis.read(buff);
      while (i != -1) {
        os.write(buff, 0, buff.length);
        os.flush();
        i = bis.read(buff);
      }
      log.info("文件下載成功:{}", fileName);

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (bis != null) {
        try {
          bis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 文件刪除
   *
   * @param fileName 要刪除的文件名
   * @return
   */
  public static Boolean deleteFile(String fileName) {
    File file = new File(FileConfigBean.getUploadPath() + fileName);
    if (file.exists()) {
      return file.delete();
    }
    return false;
  }
}
(4)開始測試

在這裏插入圖片描述
在這裏插入圖片描述
批量上傳
在這裏插入圖片描述
在這裏插入圖片描述
測試刪除
在這裏插入圖片描述
在這裏插入圖片描述
下載我這裏就不測試了 ,後續會放出源碼

發現問題
在這裏插入圖片描述
這裏配置了 /lei/** 的靜態資源請求 都會去 file:D://aa/ 尋找 那麼我咋去訪問項目中 例如 static下 存放的圖片或者靜態資源呢
我們可以繼續在 下邊添加 registry
也可以在yml中添加一些配置

	#spring下
  # url  以 /** 開頭的靜態資源訪問都會 到 resource 下 配置的地方去找
 mvc:
   static-path-pattern: /**
 resources:
   static-locations: classpath:/META-INF/resources/,classpath:/resources/, classpath:/static/, classpath:/public/, file:${file.uploadPath}

訪問項目中靜態資源
在這裏插入圖片描述
附上我的測試接口代碼

package com.leilei.controller;

import com.leilei.util.FileUtils;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * @author lei
 * @date 2020/5/12 14:48
 * @desc
 */
@RestController
public class FileController {


  /**
   * 實現單個文件上傳
   */
  @PostMapping("uploadOne")
  public Boolean fileUpload(@RequestParam("file") MultipartFile file) {
    return FileUtils.uploadOne(file);
  }

  /**
   * 多文件上傳
   */
  @PostMapping("uploadMore")
  public Boolean fileUploadMore(HttpServletRequest request) {
    List<MultipartFile> files = ((MultipartHttpServletRequest) request)
        .getFiles("files");
    return FileUtils.uploadMore(files);
  }

  /**
   * 文件下載
   *
   * @param res
   * @param fileName 要下載的文件名
   */
  @GetMapping("download/{fileName}")
  public void testDownload(HttpServletResponse res, @PathVariable("fileName") String fileName) {
    FileUtils.download(res, fileName);
  }

  /**
   * 文件刪除
   *
   * @param fileName 要刪除的文件名
   * @return
   */
  @GetMapping("delete/{fileName}")
  public Boolean delete(@PathVariable("fileName") String fileName) {
    return FileUtils.deleteFile(fileName);
  }
}

springboot 本地中 文件上傳下載 就完成了 !
項目中仍存在 上傳中文文件名 刪除 找不到情況 可選擇將文件名 漢字轉拼音後再上傳

    <!--漢字轉拼音-->
    <dependency>
      <groupId>com.belerweb</groupId>
      <artifactId>pinyin4j</artifactId>
      <version>2.5.0</version>
    </dependency>
package com.leilei.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author lei
 * @date 2020/5/13 11:02
 * @desc
 */
public class Chines2PingUtils {

  public static String getFirstSpell(String chinese) {
    StringBuffer pybf = new StringBuffer();
    char[] arr = chinese.toCharArray();
    HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

    for (int i = 0; i < arr.length; i++) {
      if (arr[i] > 128) {
        try {
          String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
          if (temp != null) {
            pybf.append(temp[0].charAt(0));
          }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
          e.printStackTrace();
        }
      } else {
        pybf.append(arr[i]);
      }
    }
    return pybf.toString().replaceAll("\\W", "").trim().toUpperCase();
  }

  /**
   * 獲取漢字串拼音,英文字符不變
   *
   * @param chinese
   * @return
   */
  public static String getFullSpell(String chinese) {
    StringBuffer pybf = new StringBuffer();
    char[] arr = chinese.toCharArray();
    HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    for (int i = 0; i < arr.length; i++) {
      if (arr[i] > 128) {
        try {
          pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
        } catch (BadHanyuPinyinOutputFormatCombination e) {
          e.printStackTrace();
        }
      } else {
        pybf.append(arr[i]);
      }
    }
    return pybf.toString();
  }

  public static void main(String[] args) {
    String fullSpell = Chines2PingUtils.getFullSpell("aaaaa.txt");
    System.out.println(fullSpell);
  }
}

附上項目源碼:springboot-file-upload-download

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章