這裏是一個文件上傳的工具類,通用性很強。廢話不多說,直奔主題。如有疑問或錯誤,歡迎指正交流。
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;
}
}