文件上传入门案例
页面分析
<form action="http://localhost:8091/file" method="post"
enctype="multipart/form-data">
<input name="fileImage" type="file" />
<input type="submit" value="提交"/>
</form>
编辑FileController
@RestController
public class FileController {
/**
* 文件上传的入门案例
* url:http://localhost:8091/file
* 参数: fileImage 名称
* 返回值: 文件上传成功!!!
* SpringMVC 提供了工具API 专门操作流文件.
*
* 文件上传的具体步骤:
* 1.准备文件目录
* 2.准备文件的全名 xxxx.jpg
* 3.准备文件上传的路径 D:/JT-SOFT/images/xxxx.jpg
* 4.将字节信息输出即可.
* 大小不要超过1M
*/
@RequestMapping("/file")
public String file(MultipartFile fileImage) throws IOException {
String dirPath = "D:/JT-SOFT/images";
File dirFile = new File(dirPath);
if(!dirFile.exists()){
dirFile.mkdirs(); //一劳永逸的写法
}
//获取文件的名称
String fileName = fileImage.getOriginalFilename();
//获取文件全路径
String filePath = dirPath + "/" + fileName;
File file = new File(filePath);
fileImage.transferTo(file); //将字节信息输出到指定的位置中
return "文件上传成功!!!!";
}
}
商品文件上传实现
页面分析
准备ImageVO对象
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class ImageVO {
//{"error":0,"url":"图片的保存路径","width":图片的宽度,"height":图片的高度}
private Integer error; //错误信息 0程序运行正常 1.文件上传有误.
private String url; //图片访问的虚拟路径
private Integer width; // >0
private Integer height; // >0
//设定上传失败的方法
public static ImageVO fail(){
return new ImageVO(1,null,null,null);
}
public static ImageVO success(String url,Integer width,Integer height){
return new ImageVO(0,url,width,height);
}
}
编辑FileController
/**
* 实现文件上传
* url地址: http://localhost:8091/pic/upload?dir=image
* 参数: uploadFile: 文件的字节信息.
* 返回值: {"error":0,"url":"图片的保存路径","width":图片的宽度,"height":图片的高度}
* ImageVO对象...
*/
@RequestMapping("/pic/upload")
public ImageVO upload(MultipartFile uploadFile){
return fileService.upload(uploadFile);
}
编辑FileService
@Service
public class FileServiceImpl implements FileService{
private String rootDirPath = "D:/JT-SOFT/images";
//1.2 准备图片的集合 包含了所有的图片类型.
private static Set<String> imageTypeSet;
static {
imageTypeSet = new HashSet<>();
imageTypeSet.add(".jpg");
imageTypeSet.add(".png");
imageTypeSet.add(".gif");
}
/**
* 完善的校验的过程
* 1. 校验是否为图片
* 2. 校验是否为恶意程序
* 3. 防止文件数量太多,分目录存储.
* 4. 防止文件重名
* 5. 实现文件上传.
* @param uploadFile
* @return
*/
@Override
public ImageVO upload(MultipartFile uploadFile) {
//1.校验图片类型 jpg|png|gif..JPG|PNG....
//1.1 获取当前图片的名称 之后截取其中的类型. abc.jpg
String fileName = uploadFile.getOriginalFilename();
int index = fileName.lastIndexOf(".");
String fileType = fileName.substring(index);
//将数据转化为小写
fileType = fileType.toLowerCase();
//1.3 判断图片类型是否正确.
if(!imageTypeSet.contains(fileType)){
//图片类型不匹配
return ImageVO.fail();
}
//2.校验是否为恶意程序 根据宽度/高度进行判断
try {
//2.1 利用工具API对象 读取字节信息.获取图片对象类型
BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
//2.2 校验是否有宽度和高度
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if(width==0 || height==0){
return ImageVO.fail();
}
//3.分目录存储 yyyy/MM/dd 分隔
//3.1 将时间按照指定的格式要求 转化为字符串.
String dateDir = new SimpleDateFormat("/yyyy/MM/dd/")
.format(new Date());
//3.2 拼接文件存储的目录对象
String fileDirPath = rootDirPath + dateDir;
File dirFile = new File(fileDirPath);
//3.3 动态创建目录
if(!dirFile.exists()){
dirFile.mkdirs();
}
//4.防止文件重名 uuid.jpg 动态拼接
//4.1 动态生成uuid 实现文件名称拼接 名.后缀
String uuid =
UUID.randomUUID().toString().replace("-", "");
String realFileName = uuid + fileType;
//5 实现文件上传
//5.1 拼接文件真实路径 dir/文件名称.
String realFilePath = fileDirPath + realFileName;
//5.2 封装对象 实现上传
File realFile = new File(realFilePath);
uploadFile.transferTo(realFile);
//实现文件上传成功!!!!
String url = "https://img14.360buyimg.com/n0/jfs/t1/45882/22/7027/53284/5d49358aE9c25c1bd/fb7365463f6a1a7b.jpg";
return ImageVO.success(url,width,height);
} catch (IOException e) {
e.printStackTrace();
return ImageVO.fail();
}
}
}
页面效果展现
文件上传优化
url优化
说明:如果需要通过网络虚拟路径访问服务器,则应该按照如下的配置实现
- 本地磁盘路径: D:JT-SOFTimages20200930a.jpg
- 网络虚拟路径: http://image.jt.com20200930a.jpg
编辑pro配置文件
完成属性的动态赋值
@Service
@PropertySource("classpath:/properties/images.properties")//容器动态的加载指定的配置文件
public class FileServiceImpl implements FileService{
//由于属性的值后期可能会发生变化,所以应该动态的获取属性数据,
// 利用pro配置文件@Value("")
@Value("${image.rootDirPath}")
private String rootDirPath;//="E:/log";//定义文件的根目录
@Value("${image.urlPath}")
private String urlPath;//="http://image.jt.com";//定义虚拟路径前缀
//1.2准备图片的集合,包含了所有的图片类型
//因为集合中的图片名不能重复,所以用set集合
//如果写在方法里比较繁琐,所以用静态代码块封装图片集合
private static Set<String> imageTypeSet;
static{
imageTypeSet=new HashSet<>();
imageTypeSet.add(".jpg");
imageTypeSet.add(".png");
imageTypeSet.add(".gif");
}
/**
* 完善的校验的过程
* 1.校验是否为图片
* 2.校验是否为恶意程序
* 3.为了防止文件数量太多,分目录讯处
* 4.防止文件重名
*
* 实现文件上传
* @param uploadFile
* @return
*/
@Override
public ImageVO upload(MultipartFile uploadFile) {
//防止有多余空格,所以先做去除空格的处理
rootDirPath.trim();
urlPath.trim();
//1.校验图片类型 jpg/png/gif/... // 1.1先获取图片名,之后截取其中的类型
String fileName=uploadFile.getOriginalFilename();
int index=fileName.lastIndexOf(".");//截取“.”以后的内容
String fileType=fileName.substring(index);//获得类型:.jpg
//1.2准备图片的集合,包含了所有的图片类型
//因为集合中的图片名不能重复,所以用set集合
//如果写在方法里比较繁琐,所以用静态代码块封装图片集合
//防止文件名后缀大小写问题,将所有的数据转化为小写
fileType=fileType.toLowerCase();
//1.3 判断图片类型是否正确
//contains(fileType)表示一个元素是否属于这个集合
if(!imageTypeSet.contains(fileType)){
//图片类型不匹配
return ImageVO.fail();
}
//2.校验程序是否为恶意程序 根据宽度和高度进行判断
//2.1利用工具api对象 读取字节信息,获取图片对象类型
try {
BufferedImage bufferedImage=ImageIO.read(uploadFile.getInputStream());
//2.2校验是否有宽度和高度
int width=bufferedImage.getWidth();
int height=bufferedImage.getHeight();
if(width==0||height==0){
return ImageVO.fail();
}
//3.分目录存储 根据时间 yyyy/MM/dd 分隔
//3.1将时间按照指定的格式要求转化为字符串
String dateDir=new SimpleDateFormat("/yyyy/MM/dd/")
.format(new Date());
//3.2拼接文件存储的目录对象
String fileDirPath=rootDirPath+dateDir;
File dirFile=new File(fileDirPath);
//3.3动态创建目录
if(!dirFile.exists()){
dirFile.mkdirs();
}
//4.防止文件重名 uuid.jpg动态拼接
//4.1动态生成uuid 实现文件名称拼接 名.后缀
String uuid=
UUID.randomUUID().toString().replace("-", "");
String realFileName=uuid+fileType;
//5.实现文件上传
//5.1拼接文件真是路径 dir/文件名称
String realFilePath=fileDirPath+realFileName;
//5.2封装对象
File realFile=new File(realFilePath);
//5.3实现上传
uploadFile.transferTo(realFile);
//实现文件上传成功
//设置图片的虚拟路径
String url=urlPath+dateDir+realFileName;
return ImageVO.success(url,width,height);
}catch(Exception e){
e.printStackTrace();
return ImageVO.fail();
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。