web项目中 经常 图片上传 下面是我用到的一个自己的图片上传工具类
package com.wonder.Util; import org.apache.log4j.Logger; import org.aspectj.util.FileUtil; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; /** * Created by Guozhijie on 2016/9/23. */ public class UploadImageUitl { private static Logger logger = Logger.getLogger(UploadImageUitl.class); public static String upload(String basePath, MultipartFile file, String dir) throws IOException { //dir 保存图片文件夹 String saveFilePath = null; if (file != null) { try { //文件名 String name = file.getOriginalFilename(); //文件后缀名 String ext = name.substring(name.lastIndexOf(".") + 1).toLowerCase(); DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String format = df.format(new Date()); Random r = new Random(); for (int i = 0; i < 3; i++) { format += r.nextInt(10); } String fileName = dir + format + "." + ext; int hashCode = Math.abs(fileName.hashCode()); int dir1 = hashCode & 0xff; int dir2 = hashCode & 0xff >> 4; //存放图片路径 String uploadFilePath = basePath + File.separator + dir + File.separator + dir1 + File.separator + dir2; //访问图片路径 saveFilePath = basePath + File.separator + dir + File.separator + dir1 + File.separator + dir2 + fileName; File filePath = new File(uploadFilePath); if (!filePath.exists() && !filePath.isDirectory()) { filePath.mkdir(); } file.transferTo(new File(saveFilePath)); } catch (Exception e) { e.printStackTrace(); ; } } return saveFilePath; } }