SpringBoot-图片上传与回显

该博客介绍了如何在Spring Boot应用中实现文件上传和处理,包括在pom.xml中引入commons-fileupload和commons-io依赖,配置application.yml以限制文件上传大小,创建配置文件MyWebApplicationConfig进行虚拟映射,以及在Controller和Service层处理文件上传和预览。此外,代码展示了图片上传和预览的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.pom引入文件处理组件

在pom中导入文件上传与文件流处理组件

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
</dependency>

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
</dependency>

2.application.yml上传配置

  • 配置spring.servlet文件上传
# 文件上传
spring:
  servlet:
     multipart:
       # 单个文件大小
       max-file-size:  10MB
       # 设置总上传的文件大小
       max-request-size:  100MB
  • 配置文件上传路径
#文件上传操作
uploadfile:
  resourceFodImageHandler: /upload/app/ImageView #请求 url 中的资源映射也是保存到数据库中的父级路径
  staticAccessPath: /uploadimg/**
  location: F://ideaworkspace/fod-project/uploadFiles #自定义上传文件服务器硬盘保存路径
  # 文件上传区分
  fodCleanFile: /fod-clean-file/
  userHeadImageFile: /user-head-image-file/ # 用户头像文件

3.配置文件设置

创建一个配置文件:MyWebApplicationConfig,进行虚拟映射配置

/**
 * @author eggsy
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
	@Value("${uploadfile.resourceImageHandler}")
	private String resourceFodImageHandler;
	@Value("${uploadfile.CleanFile}")
	private String fodCleanFile;
	@Value("${uploadfile.userHeadImageFile}")
	private String userHeadImageFile;
	@Value("${uploadfile.location}")
	private String location;

	/**
	 * 虚拟映射
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {

		// 就是说 url (http://localhost:8080/flow/upload_flowChart/xxxxxxx.jpg)
		// 中出现 resourceHandler 匹配时,则映射到 location 中去,location 相当于虚拟的,被映射的路径
		// 映射本地文件时,开头必须是 file:/// 开头,表示协议
		registry.addResourceHandler(resourceFodImageHandler + "/**").addResourceLocations("file:" + location + fodCleanFile);
	}

}

4.controller层

/**
 * 图片上传工具
 *
 * @author eggsy
 */
@Slf4j
@RestController
@RequestMapping("/upload")
@Api(value = "images", tags = "图片上传工具")
public class ImageUploadController {

	@Autowired
	private ImageUploadService imageUploadService;

	/*------------- 图片上传 --------------*/
	@ApiOperation(value = "用户头像图片上传", notes = "用户头像图片上传")
	@PostMapping(value = "/app/fodCleanImageUpload", headers = "content-type=multipart/form-data")
	@ResponseBody
	public Object fodCleanImageUpload(@RequestParam(value = "images") MultipartFile[] images) throws Exception {
		if (StringUtils.isEmpty(images)) {
			return ResponseUtil.badArgument("上传");
		}
        // IMAGE_UPLOAD_FOD_CLEAN:是用来做图片来源区分的
		return imageUploadService.imageUpload(images, IMAGE_UPLOAD_FOD_CLEAN);
	}

	/**
	 * 图片预览
	 */
	@RequestMapping(value = "/app/fodImageView")
	public ResponseEntity downloadFile(String fileName, HttpServletRequest request) {
		Resource resource = imageUploadService.fodImageView(fileName);
		String contentType = null;
		try {
			contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
		} catch (IOException ex) {
			log.info("Could not determine file type.");
		}
		if (contentType == null) {
			contentType = "application/octet-stream";
		}

		return ResponseEntity.ok()
				.contentType(MediaType.parseMediaType(contentType))
				.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
				.body(resource);
	}

}

5.service层

/**
 * @author Eggsy
 */
@Service
@Slf4j
public class ImageUploadServiceImpl implements ImageUploadService {
	@Value("${uploadfile.resourceHandler}")
	private String resourceHandler;
	@Value("${uploadfile.resourceFodImageHandler}")
	private String resourceFodImageHandler;
	@Value("${uploadfile.location}")
	private String location;
	@Value("${uploadfile.fodCleanFile}")
	private String fodCleanFile;
	@Value("${uploadfile.userHeadImageFile}")
	private String userHeadImageFile;
    /**
	 * 图片上传
	 * @param images
	 * @param imageUploadFodClean
	 * @return
	 */
	@Override
	public Object imageUpload(MultipartFile[] images,Integer model) {
		List<Map<String, Object>> urlList = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < images.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			MultipartFile image = images[i];
			String path = imageUpload(image, model);
			map.put("sequence", i + 1);
			map.put("fileName", path);
			urlList.add(map);
		}
		return ResponseUtil.ok(urlList);
	}
    
	/**
	 * 图片预览
	 *
	 * @param fileName
	 * @return
	 */
	@Override
	public Resource fodImageView(String fileName) {
		log.info("file-name:" + fileName);
		try {
//			Path filePath = this.fodFileStorageLocation.resolve(fileName).normalize();
			log.info("file-path:"+this.fodFileStorageLocation.getFileName());
			Resource resource = new UrlResource("file:" + location + fileName);
			if (resource.exists()) {
				return resource;
			} else {
				throw new FileException("File not found " + fileName);
			}
		} catch (MalformedURLException ex) {
			throw new FileException("File not found " + fileName, ex);
		}
	}
	

	/**
	 * 图片上传
	 *
	 * @param image
	 * @return
	 */
	private String imageUpload(MultipartFile image, Integer model) {
		String fileName = image.getOriginalFilename();    // 文件名称
		String suffixName = fileName.substring(fileName.lastIndexOf("."));    // 图片后缀
		String filePath = null;
		if (isImageFile(suffixName)) {
			// 新图片名称
			fileName = UUID.randomUUID() + suffixName;
			// 域名访问的相对路径(通过浏览器访问的链接-虚拟路径)
			String saveToPath = null;
			// 真实路径,实际储存的路径
			String realPath = null;
			if (model == IMAGE_UPLOAD_FOD_CLEAN) {    // fod清理图片
				saveToPath = fodCleanFile + DateUtils.getDate() + "/";
				realPath = location + fodCleanFile + DateUtils.getDate() + "/";
			} else if (model == IMAGE_UPLOAD_USER_HEAD) {    // 用户头像图片
				saveToPath = userHeadImageFile + DateUtils.getDate() + "/";
				realPath = location + userHeadImageFile + DateUtils.getDate() + "/";
			}
			// 储存文件的物理路径,使用本地路径储存
			String filepath = realPath + fileName;
			// 文件保存
			FileUtils.uploadFile(image, filepath, realPath, fileName);
			filePath = saveToPath + fileName;
		}
		return filePath;
	}

	/*
	 * 	是否为图片判断
	 * */
	private Boolean isImageFile(String fileName) {
		String[] img_type = new String[]{".jpg", ".jpeg", ".png", ".bmp"};
		if (fileName == null) {
			return false;
		}
		fileName = fileName.toLowerCase();
		for (String type : img_type) {
			if (fileName.endsWith(type)) {
				return true;
			}
		}
		return false;
	}
}

6.运行结果

  1. 上传结果
    在这里插入图片描述
  2. 显示结果
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值