这里是一个文件上传的工具类,通用性很强。废话不多说,直奔主题。如有疑问或错误,欢迎指正交流。
public class FileUploadUtils {
private static final Logger logger = LoggerFactory.getLogger(FileUploadUtils.class);
public static String getUploadPath(HttpServletRequest request){
return getApplicationPath(request)+Constens.UPLOAD_FOLDER;//Contens.UPLOAD_FOLDER是一个常量upload
}
public static String getApplictionPath(HttpServletRequest request){
return request.getSession().getServletContext().getRealPath("/");
}
//保存文件
public static String saveUploadFileToDisk(MultipartFile multipartFile,HttpServletRequest request,String tempDir )throws Exception{
InputStream is = null;
OutputStream os = null;
String filePath = null;
String fileName = null;
String suffix = null;
String tempName = null;
try{
is = multipartFile.getInputStream();
fileName = multipartFile.getOriginalFilename();
suffix = fileName.substring(fileName.indexOf("."));
tempName = IdUtils.uuid32()+suffix;//Idutils.uuid32()生成唯一Id的一种算法;
filePath = createFile(request,tempName,tempDir);
os = new FileOutputStream(filePath);
byte[] b = new byte(1024);
while(is.read(b,0,b.length)>-1){
os.write(b);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(os != null){
os.flush();
os.close();
}
if(is != null){
is.close();
}
}
logger.info("文件上传路径"+filePath);
//return tempDir + File.separator + tempName;//相对路径
return filePath.replace(getFilePath(),"");
}
public static String createFile(HttpServletRequest request,String fileName,String tempDir)throws Exception{
tempDir = StringUtils.isNotBlank(tempDir)?tempDir:UUID.randomUUID().toString();
Date nowTime = new Date(System.currentTimeMillis());
SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
String retStrFormatNowDate = sdFormatter.format(nowTime);
String[] timeTemp = retstrFormatNowDate.split("-");
String path = "";
path = getFilePath()+File.separator+timeTemp[0]+File.separator+timeTemp[1]+File.separator+timeTemp[2]+File.separator+tempDir;
logger.info("临时文件夹:"+path);
File fileTemp = new File(path);
if(!tempFile.exists()){
tempFile.mkdirs;
}
String diskFileStr = path + File.separator + fileName;
logger.info("上传文件路径"+path);
File diskFile = new File(diskFileStr);
if(!diskFile.exists()){
diskFile.createNewFile();
}
return diskFileStr;
}
}