前端传输文件经后端存入数据库,后端接收注意事项
文件上传前端代码:
整体思路:
前端点击上传图片,选中图片点击上传,通过action属性跳转地址访问后端服务器,后端通过MultipartFile类型接收文件,注意此时是输入流,后端接收获取文件名字,通过正则表达式判断文件类型,符合允许上传,不符合不允许上传;根据时间创建本地文件夹,通过uuid值重命名文件,最终返回。
后端实现思路:
a.定义本地存储地址
b.获取文件名称
c.利用正则判断是否为图片
d.检查文件是否为恶意程序
e.根据时间实现目录的创建 时间yyyy-mm-dd-hh
f.使用uuid替换文件名称,保证系统内部唯一
g.实现文件上传 目录/文件名
删除,上传图片后不想上传到数据库了,中途删除,点击删除后实现本地磁盘一起删除。
以上传图片为例:
后端代码:
定义一个接收文件上传请求的controller类,创建业务层接口以及实现类,实现代码:
@Service
@PropertySource("classpath:/image.properties")
public class FileServiceImpl implements FileService{
//封装路径的前缀
//定义本地存储地址
@Value("${image.localDir}")
private String localDir; //= "J:/workspace/images";
@Value("${image.preUrl}")
private String preUrl; //= "http://image.jt.com";
/**
* 1.校验是否为图片
* 2.木马.exe.jpg 校验是否为恶意程序
* 3.为了提高查询效率,要求分目录存储
* 4.防止文件重名,使用UUID代替文件名称
*/
@Override
public ImageVO upload(MultipartFile file){
//获取图片名称
String fileName = file.getOriginalFilename();
//利用正则表达式判断是否为图片
if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
return null;
}
//检查文件是否为恶意程序
try {
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
//通过图片固有长宽属性判断是否为图片
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if(width ==0 || height == 0){
//说明不是照片
return null;
}
//根据时间实现目录的创建 时间yyyy-mm-dd-hh
String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
String localDirPath = localDir + dateDir;
File dirFile = new File(localDirPath);
if(!dirFile.exists()){
dirFile.mkdirs();
}
//使用uuid替换文件名称
//唯一:系统内部唯一
String uuid = UUID.randomUUID().toString().replace("-", "");
//截取文件后缀
int index = fileName.lastIndexOf(".");
//获取类型
String fileType = fileName.substring(index);
String newFileName = uuid + fileType;
//实现文件上传 目录/文件名
String readFilePath = localDirPath + newFileName;
file.transferTo(new File(readFilePath));
//封装返回值
/**
* 封装虚拟路径 在各个系统之间可以灵活切换,只保存动态变化的目录
* path = 时间/uuid.type
*/
String virtualPath = dateDir + newFileName;
String urlPath =preUrl + virtualPath;
System.out.println(readFilePath);
System.out.println(urlPath);
return new ImageVO(virtualPath,urlPath,newFileName);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 实现思路:
* 1.根据虚拟地址,拼接磁盘地址
* 2.判断文件是否存在
* 3.实现文件删除
* @param virtualPath
*/
@Override
public void deleteFile(String virtualPath) {
String path = localDir + virtualPath;
File file = new File(path);
if(file.exists()){
file.delete();
}
}