如何使springboot上傳文件
由於對高大上的前端處理不太熟悉,想直接透過MVC的方式進行內容傳遞,因此選用了Thymeleaf模版處理向前端傳值的問題。
application.properties檔案
#访问超市时间的设置ribbon. ConnectTimeout=60000ribbon. ReadTimeout=60000 # 开启多文件上传 spring.servlet.multipart. enabled=true spring.servlet.multipart.file-size-threshold =0 #单个文件大小 #spring.http.multipart.maxFileSize=10MB #设置总上传的数据大小 #spring.http.multipart.maxRequestSize=10MB #升级到2.0后需要改成 #单个文件大小spring.servlet. multipart.max-file-size=10Mb #设置总上传的数据大小 spring.servlet.multipart. max-request-size=10Mb #上传路径upload_path=D:/file_statics #下载路径download_path=D:/file_statics
2.controller程式碼
import java.io. BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream. Collectors;import javax.servlet. http.HttpServletResponse;import org. apache.commons.lang3.StringUtils; import org.springframework.beans. factory.annotation.Value;import org. springframework.web.bind.annotation. RequestMapping;import org.springframework. web.bind.annotation.RequestMethod;import org. springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation. ResponseBody;import org.springframework.web. bind.annotation.RestController;import org. springframework.web.multipart.MultipartFile; import org.springframework.web.servlet. mvc.support.RedirectAttributes;import com. vinord.common.model.ResultView;import com. vinord.common.util.Constains;@RestController public class FileUploadController { @Value("${upload_path}") private final String upload_path ="D:/file_statics"; @Value("${download_path}") private final String download_path ="D:/file_statics"; /** * 单个文件上传 * @param file * @param redirectAttributes * @return */ @RequestMapping("uploadFile") public ResultView singleFileUpload(@RequestParam("file") MultipartFile file,RedirectAttributes redirectAttributes) { ResultView result = new ResultView(); if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "请选择文件进行上传"); result.setCode(Constains.STATUS_ZERO); result.setMsg("请选择文件进行上传!"); return result; } try { byte[] bytes = file.getBytes(); String filename = file.getOriginalFilename(); String name = filename.substring(0,filename.lastIndexOf(".")); String formatDate = System.currentTimeMillis()+""; int index = filename.indexOf("."); String savefilename = name + formatDate+ filename.substring(index); Path path = Paths.get(upload_path+ File.separator+savefilename); Files.write(path, bytes); redirectAttributes.addFlashAttribute("message","成功上传文件: '" + file.getOriginalFilename() + "'"); result.setCode(Constains.STATUS_ONE); result.setMsg("上传成功"); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 多个文件上传 * @param files * @return */ @ResponseBody @RequestMapping(value = "/upload/batch", method = RequestMethod.POST) public ResultView batchUpload(@RequestParam("files")MultipartFile[] files) { ResultView result = new ResultView(); String uploadedFileName = Arrays.stream(files).map(x -> x.getOriginalFilename()) .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , ")); if (StringUtils.isEmpty(uploadedFileName)) { result.setCode(Constains.STATUS_ZERO); result.setMsg("文件上传失败,文件为空!"); return result; } try { saveUploadedFiles(Arrays.asList(files)); } catch (IOException e) { result.setCode(Constains.STATUS_ZERO); result.setMsg("文件上传异常"+e.getMessage()); return result; } result.setCode(Constains.STATUS_ONE); result.setMsg("上传成功"); return result; } private void saveUploadedFiles(List<MultipartFile> files) throws IOException { for (MultipartFile file : files) { if (file.isEmpty()) { continue; } byte[] bytes = file.getBytes(); String filename = file.getOriginalFilename(); String name = filename.substring(0,filename.lastIndexOf(".")); String formatDate = System.currentTimeMillis()+""; int index = filename.indexOf("."); String savefilename = name + formatDate+ filename.substring(index); Path path = Paths.get(upload_path+ File.separator+ savefilename); Files.write(path, bytes); } } /** * 下载 * @param res * @throws IOException */ @RequestMapping("download") public void download(HttpServletResponse res) throws IOException { String fileName = "CustomLogControl1536898060373.java"; 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(download_path+ File.separator+fileName))); int i = bis.read(buff); while (i != -1) { os.write(buff, 0, buff.length); os.flush(); i = bis.read(buff); } } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
相關建議:
SpringBoot Thymeleaf實作html檔案引入(類似include功能)_html/css_WEB-ITnose
#以上是如何使springboot上傳文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

Java 8引入了Stream API,提供了一種強大且表達力豐富的處理數據集合的方式。然而,使用Stream時,一個常見問題是:如何從forEach操作中中斷或返回? 傳統循環允許提前中斷或返回,但Stream的forEach方法並不直接支持這種方式。本文將解釋原因,並探討在Stream處理系統中實現提前終止的替代方法。 延伸閱讀: Java Stream API改進 理解Stream forEach forEach方法是一個終端操作,它對Stream中的每個元素執行一個操作。它的設計意圖是處

膠囊是一種三維幾何圖形,由一個圓柱體和兩端各一個半球體組成。膠囊的體積可以通過將圓柱體的體積和兩端半球體的體積相加來計算。本教程將討論如何使用不同的方法在Java中計算給定膠囊的體積。 膠囊體積公式 膠囊體積的公式如下: 膠囊體積 = 圓柱體體積 兩個半球體體積 其中, r: 半球體的半徑。 h: 圓柱體的高度(不包括半球體)。 例子 1 輸入 半徑 = 5 單位 高度 = 10 單位 輸出 體積 = 1570.8 立方單位 解釋 使用公式計算體積: 體積 = π × r2 × h (4
