SpringBoot後台實現檔案上傳下載,springboot檔案上傳

來源:互聯網
上載者:User

SpringBoot後台實現檔案上傳下載,springboot檔案上傳

SpringBoot後台如何?檔案上傳下載?

最近做的一個項目涉及到檔案上傳與下載。前端上傳採用百度webUploader外掛程式。有關該外掛程式的使用方法還在研究中,日後整理再記錄。本文主要介紹SpringBoot後台對檔案上傳與下載的處理。

單檔案上傳

// 單檔案上傳@RequestMapping(value = "/upload")@ResponseBodypublic 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);  // 設定檔案儲存體路徑  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)@ResponseBodypublic 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())));//設定檔案路徑及名字        stream.write(bytes);// 寫入        stream.close();      } catch (Exception e) {        stream = null;        return "第 " + i + " 個檔案上傳失敗 ==> "            + e.getMessage();      }    } else {      return "第 " + i          + " 個檔案上傳失敗因為檔案為空白";    }  }  return "上傳成功";}

檔案下載

//檔案下載相關代碼@RequestMapping("/download")public String downloadFile(HttpServletRequest request, HttpServletResponse response) {  String fileName = "aim_test.txt";// 設定檔案名稱,根據業務需要替換成要下載的檔案名稱  if (fileName != null) {    //設定檔案路徑    String realPath = "D://aim//"    File file = new File(realPath , fileName);    if (file.exists()) {      response.setContentType("application/force-download");// 設定強制下載不開啟      response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設定檔案名稱      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配置類對檔案上傳進行全域控制。

@Configurationpublic class MultipartConfig {  @Bean  public MultipartConfigElement multipartConfigElement() {    MultipartConfigFactory factory = new MultipartConfigFactory();    // 置檔案大小限制 ,超出此大小頁面會拋出異常資訊    factory.setMaxFileSize("2MB"); //KB,MB    // 設定總上傳資料總大小    factory.setMaxRequestSize("20MB");    // 設定檔案臨時檔案夾路徑    // factory.setLocation("E://test//");    // 如果檔案大於這個值,將以檔案的形式儲存,如果小於這個值檔案將儲存在記憶體中,預設為0    // factory.setMaxRequestSize(0);    return factory.createMultipartConfig();  }}

注意事項

前後端檔案傳輸格式應為 multipart/form-data

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.