java上传图片工具类
程序员文章站
2024-02-19 11:10:52
...
package com.findmiThree.utils.uploadimg;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.web.multipart.MultipartFile;
/**
* 上传图片工具类
*
* @author Administrator
*
*/
public class TaoGouUpLoadImgUtils {
/**
*
* @param filePath //上传文件磁盘路径
* @param files //文件流
* @return
*/
public static String uploadImg(String filePath, MultipartFile files, String typePath) {
String imgUrl = "";
try {
// 获取文件原始名称
String fileName = files.getOriginalFilename();
// 时间戳重新命名
String dataTimes = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
fileName = dataTimes + "_" + fileName;
String savePath = filePath + typePath + "/" + dataTimes;
File myfilePath = new File(savePath);
if (!myfilePath.exists()) {
myfilePath.mkdirs();
}
savePath = savePath + "/" + fileName;
File targetFile = new File(savePath);
files.transferTo(targetFile);
imgUrl = "/" + typePath + "/" + dataTimes + "/" + fileName;
if (!targetFile.exists()) {
targetFile.mkdir();
} else {
return imgUrl;
}
} catch (Exception e) {
e.printStackTrace();
}
return imgUrl;
}
}