很多项目都需要上传文件,特别是图片,那么,如何方便快捷的实现文件的上传和回显呢?Spring为我们提供了MultipartFile类,方便又好用
一、添加yml配置
yml配置中主要是指定文件上传的路径,大小的限制等方面,配置如下:
spring:
#图片上传
#启用图片上传功能
servlet:
multipart:
enabled: true
#上传路径
location: D://upload
#指定上传文件大小
max-file-size: 1Mb
#指定最大允许请求的大小
max-request-size: 10Mb
因为是spring提供的功能所以我们不需要依赖第三方jar包,直接配置上了就可以使用,非常的简单易用
二、实现文件上传
实现的思路很简单,和我们的日常写的mvc项目一样,只需要在Controller层方法中注入MultipartFile对象,接下来使用MultipartFile对象具体操作上传的方法就可以了,在上传文件的时候有如下建议:
1、不使用原文件名,用一个不重复的字符串表示上传后的文件名(如UUID或者当前时间的毫秒值+随机数都可以)
2、保存图片的文件夹命名要有规律性,方便维护和查找(如当前日期)
3、如果是指定的上传图片或者某种格式的文件需要在方法中做验证,防止木马共计(在这里的例子满足通用文件上传就不验证了)代码如下:
controller层:
package com.wwy.test.upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.wwy.entry.APIEntry;
import com.wwy.test.upload.service.UpLoadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;