ImageUtil

时间:2023-03-08 23:48:55
ImageUtil
package com.rscode.credits.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List; import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
/**
* 图片工具
* @author tn
* @RequestParam("file")CommonsMultipartFile file
*
*/ public class ImageUtil { private static List<String> image = new ArrayList<>(Arrays.asList("PNG","JPEG","JPG","GIF","BMP")); /**
* 上传图片文件(PNG,JPEG,JPG,GIF)
* @param file 文件
* @param imagePath 图片存储路径
* @return newFileNamePath返回文件的相对路径 (自定义目录/xx.jpg)
* return null 没有图片
* return erro 图片格式有误
* return excp 上传失败
* return 返回文件名
*/
public static String filePut(MultipartFile file,String imagePath){
//获取前端文件名
String fileName = file.getOriginalFilename();//获取上传文件的文件名
String end = fileName.substring(fileName.lastIndexOf(".")+1).toUpperCase();//判断图片后缀是否正确 if(file.isEmpty()){//fileName.equals("")||fileName==null
System.out.println("没有图片");
return null;
}else if(image.contains(end)){
String newFileName =new Date().getTime()+"."+end; // 新文件名 end后缀
File f = new File(imagePath);
if (!f.exists()) //服务器中文件不存在就创建
f.mkdirs();
if (!file.isEmpty()) { //文件不为空
try {
//保存文件
file.transferTo(new File(imagePath + newFileName));
} catch (Exception e) {
e.printStackTrace();
return "excp";
}
}
return newFileName;//返回图片新名字
} else { return "erro";
} } /**
* 到存放图片的文件夹下面删除图片
*
* @param fileName
* @return
*/
public static boolean fileDelete(String imagePath) {
if (imagePath == null) {
return false;
}
try {
//强制删除方法
FileUtils.forceDelete(new File(imagePath));
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
} // public static void main(String[] args) {
// imageUtil.fileDelete("C:\\Users\\en\\Desktop\\WORK\\Image\\activity\\b - 副本.jpg");
// }
}