如何使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

Spring Boot简化了可靠,可扩展和生产就绪的Java应用的创建,从而彻底改变了Java开发。 它的“惯例惯例”方法(春季生态系统固有的惯例),最小化手动设置
