springmvc上传方法

时间:2022-04-30 07:56:34
/**
*
* @param file 上传的文件
* @param filePath 上传到那个目录
* @return 上传后的文件名字
* @throws IOException
*/
public static String uploadFileToPath( MultipartFile file, String filePath) throws IOException {
//获取图片原始名称 1.jpg
String originalFilename = file.getOriginalFilename();
//图片扩展名 jsp
int lastIndexOf = originalFilename.lastIndexOf(".");
//String types = originalFilename.substring(originalFilename.lastIndexOf(".")+1).toLowerCase();
String newFileName = "";
if(lastIndexOf != -1) {
newFileName = new Date().getTime() + originalFilename.substring(lastIndexOf);
}else {
newFileName = new Date().getTime() + ".tmp";
} String fullPath = filePath + newFileName; // 创建文件夹
File dirPath = new File(filePath);
if (!dirPath.exists() || (!dirPath.isDirectory())) {
dirPath.mkdirs();
}
//创建文件
File uploadFile = new File(fullPath);
//Copy文件
FileCopyUtils.copy(file.getBytes(), uploadFile); return newFileName;
}