文件上传
前端页面
<body>
<h1>实现文件长传</h1>
<!--enctype="开启多媒体标签" -->
<form action="http://localhost:8081//pic/upload" method="post"
enctype="multipart/form-data">
<input name="fileImage" type="file" />
<input type="submit" value="提交"/>
</form>
</body>
enctype=“multipart/form-data”
enctype--------------encodetype就是编码类型的意思
multipart/form-data-----是将文件以二进制的形式上传,这样可以实现多种类型的文件上传。
后端实现
创建controller
@Autowired
private FileService fileService;
@RequestMapping("/pic/upload")
public ImageVO upload(MultipartFile uploadFile){
return fileService.upload(uploadFile);
}
单文件MultipartFile file
多文件(定义为数组形式)MultipartFile[] file
步骤:
- 判断文件是否为空:!file.isEmpty() – 不为空
- 文件保存路径 :String filePath = 文件夹目录 +file.getOriginalFilename();
- 上传文件原名:file.getOriginalFilename();
- 存储文件:file.transferTo(new File(filePath));
封装返回的实体类
package com.jt.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @author mass
* @date 2020/11/5 15:37
*/
@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);
}
}
properties配置文件
image.rootDirPath=F:/JT-SOFT/images
image.urlPath=http://image.jt.com`
创建service
package com.jt.service;
import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* @author mass
* @date 2020/11/5 15:47
*/
@Service
@PropertySource("classpath:/properties/image.properties") //容器动态加载指定的配置文件
public class FileServiceImpl implements FileService {
@Value("${image.rootDirPath}") //加载文件存储根路径
private String rootDirPath; // = "F:/JT-SOFT/images";
@Value("${image.urlPath}") //虚拟路径域名
private String urlPath; // = "http://image.jt.com"
//1.2 准备图片的集合 包含了所有的图片类型.
private static Set<String> imageTypeSet;
static {
imageTypeSet = new HashSet<>();
imageTypeSet.add(".jpg");
imageTypeSet.add(".png");
imageTypeSet.add(".jpeg");
imageTypeSet.add(".gif");
}
/**
* 图片上传过程
* 1. 校验是否为图片
* 2. 校验是否为恶意程序
* 3. 防止文件数量太多,分目录存储.
* 4. 防止文件重名
* 5. 实现文件上传.
*
* @param uploadFile
* @return
*/
@Override
public ImageVO upload(MultipartFile uploadFile) {
//1.校验图片类型
//获取图片名称,截取图片类型
String fileName = uploadFile.getOriginalFilename();
int index = fileName.lastIndexOf(".");
String fileType = fileName.substring(index);
//数据转化小写
fileType = fileType.toLowerCase();
//判断图片类型是否正确
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.分目录存储 按日期分目录
//3.1 将时间按照指定的格式要求 转化为字符串.
String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
String fileDirPath = rootDirPath + dateDir;
File dirFile = new File(fileDirPath);
//3.3 动态创建目录
if (!dirFile.exists()){
dirFile.mkdirs();
}
//4.防止文件重名 uuid.jpg 动态凭借,生成动态名称
String uuid = UUID.randomUUID().toString().replace("-", "");
String realFileName = uuid+fileType;
//5.实现文件上传
String realFilePath = fileDirPath + realFileName;
//封装对象,实现上传
File realFile = new File(realFilePath);
uploadFile.transferTo(realFile);
//实现文件上传成功
//真实地址:-----文件存放地址
// rootDirPath + dateDir + realFileName
//虚拟地址:------生成http协议可访问的虚拟地址,放入数据库,用于访问,使用nginx反向代理,获取图片真实地址,回显图片。
String url = urlPath+dateDir+realFileName;
return ImageVO.success(url,width,height);
} catch (IOException e) {
e.printStackTrace();
return ImageVO.fail();
}
}
}