springmvc 图片上传、展示及下载
1、需要添加在pom.xml中添加
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
2、需要在spring.xml配置文件中设置文件可上传的最大文件
<!-- 配置文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 配置文件上传的最大体积 30M --> <property name="maxUploadSize" value="30720000"></property> </bean>
3、上传文件类
package com.tn.controller; import com.tn.entity.po.UploadPO; import com.tn.result.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.UUID; /** * @author :abel.he * @date :Created in 2021/12/22 14:09 * @description:文件上传 * @modified By: */ @RestController @Slf4j public class UploadController { @Value("${file.upload.path}") private String fileUploadPath; @PostMapping("upload") public Result upload(MultipartFile file) { // 原始文件名 String originalFileName = file.getOriginalFilename(); // 获取图片后缀 String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")); // 生成图片存储的名称,UUID 避免相同图片名冲突,并加上图片后缀 String fileName = UUID.randomUUID().toString() + suffix; // 图片存储路径 String filePath = fileUploadPath + fileName; File saveFile = new File(filePath); try { // 将上传的文件保存到服务器文件系统 file.transferTo(saveFile); // 记录服务器文件系统图片名称 } catch (IOException e) { log.error(e.getMessage(), e); } UploadPO uploadPO = new UploadPO(); uploadPO.setFilePath(filePath); uploadPO.setFileName(originalFileName); uploadPO.setSaveFilePath(""); return Result.success(uploadPO); } /** * 处理图片显示请求 * @param fileName */ @RequestMapping("/showPic/{fileName}.{suffix}") public void showPicture(@PathVariable("fileName") String fileName, @PathVariable("suffix") String suffix, HttpServletResponse response){ File imgFile = new File(fileUploadPath + fileName + "." + suffix); responseFile(response, imgFile); } /** * 处理图片下载请求 * @param fileName * @param response */ @GetMapping("/downloadPic/{fileName}.{suffix}") public void downloadPicture(@PathVariable("fileName") String fileName, @PathVariable("suffix") String suffix, HttpServletResponse response){ // 设置下载的响应头信息 response.setHeader("Content-Disposition", "attachment;fileName=" + "headPic.jpg"); File imgFile = new File(fileUploadPath + fileName + "." + suffix); responseFile(response, imgFile); } /** * 响应输出图片文件 * @param response * @param imgFile */ private void responseFile(HttpServletResponse response, File imgFile) { try(InputStream is = new FileInputStream(imgFile); OutputStream os = response.getOutputStream();){ byte [] buffer = new byte[1024]; while(is.read(buffer) != -1){ os.write(buffer); } os.flush(); } catch (IOException ioe){ ioe.printStackTrace(); } } }
参考资料: