Java FileUploadUtil工具類詳解
本文實例為大家分享了FileUploadUtil工具類的具體代碼,供大家參考,具體內(nèi)容如下
package com.gootrip.util; import java.io.File; import java.util.*; import org.apache.commons.fileupload.*; import javax.servlet.http.HttpServletRequest; import java.util.regex.Pattern; import java.io.IOException; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import java.util.regex.Matcher; public class FileUploadUtil { //當(dāng)上傳文件超過限制時設(shè)定的臨時文件位置,注意是絕對路徑 private String tempPath = null; //文件上傳目標(biāo)目錄,注意是絕對路徑 private String dstPath = null; //新文件名稱,不設(shè)置時默認(rèn)為原文件名 private String newFileName = null; //獲取的上傳請求 private HttpServletRequest fileuploadReq = null; //設(shè)置最多只允許在內(nèi)存中存儲的數(shù)據(jù),單位:字節(jié),這個參數(shù)不要設(shè)置太大 private int sizeThreshold = 4096; //設(shè)置允許用戶上傳文件大小,單位:字節(jié) //共10M private long sizeMax = 10485760; //圖片文件序號 private int picSeqNo = 1; private boolean isSmallPic = false; public FileUploadUtil(){ } public FileUploadUtil(String tempPath, String destinationPath){ this.tempPath = tempPath; this.dstPath = destinationPath; } public FileUploadUtil(String tempPath, String destinationPath, HttpServletRequest fileuploadRequest){ this.tempPath = tempPath; this.dstPath = destinationPath; this.fileuploadReq = fileuploadRequest; } /** 文件上載 * @return true —— success; false —— fail. */ public boolean Upload(){ DiskFileItemFactory factory = new DiskFileItemFactory(); try { //如果沒有上傳目的目錄,則創(chuàng)建它 FileUtil.makeDirectory(dstPath+"/ddd"); /*if (!FileUtil.makeDirectory(dstPath+"/ddd")) { throw new IOException("Create destination Directory Error."); }*/ //如果沒有臨時目錄,則創(chuàng)建它 FileUtil.makeDirectory(tempPath+"/ddd"); /*if (!FileUtil.makeDirectory(tempPath+"/ddd")) { throw new IOException("Create Temp Directory Error."); }*/ //上傳項目只要足夠小,就應(yīng)該保留在內(nèi)存里。 //較大的項目應(yīng)該被寫在硬盤的臨時文件上。 //非常大的上傳請求應(yīng)該避免。 //限制項目在內(nèi)存中所占的空間,限制最大的上傳請求,并且設(shè)定臨時文件的位置。 //設(shè)置最多只允許在內(nèi)存中存儲的數(shù)據(jù),單位:字節(jié) factory.setSizeThreshold(sizeThreshold); // the location for saving data that is larger than getSizeThreshold() factory.setRepository(new File(tempPath)); ServletFileUpload upload = new ServletFileUpload(factory); //設(shè)置允許用戶上傳文件大小,單位:字節(jié) upload.setSizeMax(sizeMax); List fileItems = upload.parseRequest(fileuploadReq); // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server Iterator iter = fileItems.iterator(); // 正則匹配,過濾路徑取文件名 String regExp = ".+\\\\(.+)$"; // 過濾掉的文件類型 String[] errorType = {".exe", ".com", ".cgi", ".asp", ".php", ".jsp"}; Pattern p = Pattern.compile(regExp); while (iter.hasNext()) { System.out.println("++00++====="+newFileName); FileItem item = (FileItem) iter.next(); //忽略其他不是文件域的所有表單信息 if (!item.isFormField()) { String name = item.getName(); System.out.println("++++====="+name); long size = item.getSize(); //有多個文件域時,只上傳有文件的 if ((name == null || name.equals("")) && size == 0) continue; Matcher m = p.matcher(name); boolean result = m.find(); if (result) { for (int temp = 0; temp < errorType.length; temp++) { if (m.group(1).endsWith(errorType[temp])) { throw new IOException(name + ": Wrong File Type"); } } String ext = "."+FileUtil.getTypePart(name); try { //保存上傳的文件到指定的目錄 //在下文中上傳文件至數(shù)據(jù)庫時,將對這里改寫 //沒有指定新文件名時以原文件名來命名 if (newFileName == null || newFileName.trim().equals("")) { item.write(new File(dstPath +"/"+ m.group(1))); } else { String uploadfilename = ""; if (isSmallPic) { uploadfilename = dstPath +"/"+ newFileName+"_"+picSeqNo+"_small"+ext; } else { uploadfilename = dstPath +"/"+ newFileName+"_"+picSeqNo+ext; } //生成所有未生成的目錄 System.out.println("++++====="+uploadfilename); FileUtil.makeDirectory(uploadfilename); //item.write(new File(dstPath +"/"+ newFileName)); item.write(new File(uploadfilename)); } picSeqNo++; //out.print(name + " " + size + "<br>"); } catch (Exception e) { //out.println(e); throw new IOException(e.getMessage()); } } else { throw new IOException("fail to upload"); } } } } catch (IOException e) { System.out.println(e); } catch (FileUploadException e) { System.out.println(e); } return true; } /**從路徑中獲取單獨文件名 * @author * * TODO 要更改此生成的類型注釋的模板,請轉(zhuǎn)至 * 窗口 - 首選項 - Java - 代碼樣式 - 代碼模板 */ public String GetFileName(String filepath) { String returnstr = "*.*"; int length = filepath.trim().length(); filepath = filepath.replace('\\', '/'); if(length >0) { int i = filepath.lastIndexOf("/"); if (i >= 0) { filepath = filepath.substring(i + 1); returnstr = filepath; } } return returnstr; } /** * 設(shè)置臨時存貯目錄 */ public void setTmpPath(String tmppath) { this.tempPath = tmppath; } /** * 設(shè)置目標(biāo)目錄 */ public void setDstPath(String dstpath) { this.dstPath = dstpath; } /** * 設(shè)置最大上傳文件字節(jié)數(shù),不設(shè)置時默認(rèn)10M */ public void setFileMaxSize(long maxsize) { this.sizeMax = maxsize; } /** * 設(shè)置Http 請求參數(shù),通過這個能數(shù)來獲取文件信息 */ public void setHttpReq(HttpServletRequest httpreq) { this.fileuploadReq = httpreq; } /** * 設(shè)置Http 請求參數(shù),通過這個能數(shù)來獲取文件信息 */ public void setNewFileName(String filename) { this.newFileName = filename; } /** * 設(shè)置此上傳文件是否是縮略圖文件,這個參數(shù)主要用于縮略圖命名 */ public void setIsSmalPic(boolean isSmallPic) { this.isSmallPic = isSmallPic; } /** * 設(shè)置Http 請求參數(shù),通過這個能數(shù)來獲取文件信息 */ public void setPicSeqNo(int seqNo) { this.picSeqNo = seqNo; } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- java常用工具類之DES和Base64加密解密類
- java正則表達(dá)式表單驗證類工具類(驗證郵箱、手機號碼、qq號碼等)
- java連接數(shù)據(jù)庫增、刪、改、查工具類
- java使用jdbc連接數(shù)據(jù)庫工具類和jdbc連接mysql數(shù)據(jù)示例
- java常用工具類之?dāng)?shù)據(jù)庫連接類(可以連接多種數(shù)據(jù)庫)
- java實現(xiàn)excel導(dǎo)入數(shù)據(jù)的工具類
- java常用工具類之Excel操作類及依賴包下載
- Java中StringUtils工具類的一些用法實例
- java文件操作工具類分享(file文件工具類)
- java工具類之實現(xiàn)java獲取文件行數(shù)
相關(guān)文章
Java實戰(zhàn)角色權(quán)限后臺腳手架系統(tǒng)的實現(xiàn)流程
只學(xué)書上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+Springboot+Maven+myBaits-Plus+Vue+Element-UI+Mysql實現(xiàn)一個角色權(quán)限后臺腳手架系統(tǒng),大家可以在過程中查缺補漏,提升水平2022-01-01Java 8中Collectors.toMap空指針異常源碼解析
這篇文章主要為大家介紹了Java 8中Collectors.toMap空指針異常源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08SpringBoot 注解事務(wù)聲明式事務(wù)的方式
springboot使用上述注解的幾種方式開啟事物,可以達(dá)到和xml中聲明的同樣效果,但是卻告別了xml,使你的代碼遠(yuǎn)離配置文件。今天就扒一扒springboot中事務(wù)使用注解的玩法,感興趣的朋友一起看看吧2017-09-09Springboot攔截器如何獲取@RequestBody參數(shù)
這篇文章主要介紹了Springboot攔截器如何獲取@RequestBody參數(shù)的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06詳解tryAcquire()、addWaiter()、acquireQueued()
這篇文章主要tryAcquire()、addWaiter()、acquireQueued()的用法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03Java使用itext5實現(xiàn)PDF表格文檔導(dǎo)出
這篇文章主要介紹了Java使用itext5實現(xiàn)PDF表格文檔導(dǎo)出,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01SpringBoot項目部署到服務(wù)器上的方法(Jar包)
這篇文章主要介紹了SpringBoot項目部署到服務(wù)器上的方法(Jar包),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01關(guān)于任務(wù)調(diào)度框架quartz使用(異常處理,解決恢復(fù)后多次調(diào)度處理)
這篇文章主要介紹了關(guān)于任務(wù)調(diào)度框架quartz使用(異常處理,解決恢復(fù)后多次調(diào)度處理),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12