溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用SpringBoot怎么實現(xiàn)文件上傳與下載

發(fā)布時間:2021-05-27 17:57:14 來源:億速云 閱讀:131 作者:Leah 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)使用SpringBoot怎么實現(xiàn)文件上傳與下載,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

單文件上傳

/ 單文件上傳
@RequestMapping(value = "/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
  try {
  if (file.isEmpty()) {
    return "文件為空";
  }
  // 獲取文件名
  String fileName = file.getOriginalFilename();
  logger.info("上傳的文件名為:" + fileName);
  // 獲取文件的后綴名
  String suffixName = fileName.substring(fileName.lastIndexOf("."));
  logger.info("文件的后綴名為:" + suffixName);

  // 設(shè)置文件存儲路徑
  String filePath = "D://aim//";
  String path = filePath + fileName + suffixName;

  File dest = new File(path);
  // 檢測是否存在目錄
  if (!dest.getParentFile().exists()) {
    dest.getParentFile().mkdirs();// 新建文件夾
  }
  file.transferTo(dest);// 文件寫入
  return "上傳成功";
  } catch (IllegalStateException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return "上傳失敗";
}

如果想要修改文件路徑及文件名,修改filePath以及fileName即可。

多文件上傳

/多文件上傳
@RequestMapping(value = "/uploadMore", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(HttpServletRequest request) {
  List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
  MultipartFile file = null;
  BufferedOutputStream stream = null;
  for (int i = 0; i < files.size(); ++i) {
    file = files.get(i);
    String filePath = "D://aim//";
    if (!file.isEmpty()) {
      try {
        byte[] bytes = file.getBytes();
        stream = new BufferedOutputStream(new FileOutputStream(
            new File(filePath + file.getOriginalFilename())));//設(shè)置文件路徑及名字
        stream.write(bytes);// 寫入
        stream.close();
      } catch (Exception e) {
        stream = null;
        return "第 " + i + " 個文件上傳失敗 ==> "
            + e.getMessage();
      }
    } else {
      return "第 " + i
          + " 個文件上傳失敗因為文件為空";
    }
  }
  return "上傳成功";
}

文件下載

//文件下載相關(guān)代碼
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
  String fileName = "aim_test.txt";// 設(shè)置文件名,根據(jù)業(yè)務(wù)需要替換成要下載的文件名
  if (fileName != null) {
    //設(shè)置文件路徑
    String realPath = "D://aim//"
    File file = new File(realPath , fileName);
    if (file.exists()) {
      response.setContentType("application/force-download");// 設(shè)置強(qiáng)制下載不打開
      response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設(shè)置文件名
      byte[] buffer = new byte[1024];
      FileInputStream fis = null;
      BufferedInputStream bis = null;
      try {
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        OutputStream os = response.getOutputStream();
        int i = bis.read(buffer);
        while (i != -1) {
          os.write(buffer, 0, i);
          i = bis.read(buffer);
        }
        System.out.println("success");
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        if (bis != null) {
          try {
            bis.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (fis != null) {
          try {
            fis.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
  return null;
}

MultipartConfig配置

可以通過MultipartConfig配置類對文件上傳進(jìn)行全局控制。

@Configuration
public class MultipartConfig {

  @Bean
  public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    // 置文件大小限制 ,超出此大小頁面會拋出異常信息
    factory.setMaxFileSize("2MB"); //KB,MB
    // 設(shè)置總上傳數(shù)據(jù)總大小
    factory.setMaxRequestSize("20MB");
    // 設(shè)置文件臨時文件夾路徑
    // factory.setLocation("E://test//");
    // 如果文件大于這個值,將以文件的形式存儲,如果小于這個值文件將存儲在內(nèi)存中,默認(rèn)為0
    // factory.setMaxRequestSize(0);
    return factory.createMultipartConfig();
  }
}

關(guān)于使用SpringBoot怎么實現(xiàn)文件上傳與下載就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI