Java工具類之檔案上傳__Java

來源:互聯網
上載者:User
  這裡是一個檔案上傳的工具類,通用性很強。廢話不多說,直奔主題。如有疑問或錯誤,歡迎指正交流。

 

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;
}
 
}


 


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.