[版權申明:本文系做者原創,轉載請註明出處]
文章出處:http://blog.csdn.net/sdksdk0/article/details/52048666
做者:朱培 ID:sdksdk0 郵箱: zhupei@tianfang1314.cn javascript
本文主要從javaweb上傳文件到服務器中,而且在服務器端進行數據文件存儲,主要分享了文件上傳原理、使用第三方開源工具進行上傳以及一些文件上傳時須要注意的地方,文件的優化處理,還有簡易分享了從咱們剛纔上傳進去的文件進行下載。須要掌握基本的開發流程,底層實現原理等。php
告知服務器請求正文的MIME類型。
application/x-www-form-urlencoded(默認):
正文:name=aa&password=123
服務器獲取數據:request.getParameter(「name」);html
解析請求正文的每部分的內容。java
基於html form表單上傳的數據都是以相似—————————–7da3c8e180752{0x130x10}這樣的分割符來標記一塊數據的起止。
git
文件上傳的Content-Type爲multipart/form-data; boundary=—-WebKitFormBoundaryhQslmBE7nbTLTJzD,而普通的form表單的Content-Type爲application/x-www-form-urlencoded。所以,咱們能夠利用HttpServletRequest的request.getHeaderNames()方法和request.getHeaders(headName)方法獲得請求頭Headers中的Content-Type數據,而後根據Content-Type數據中是否包含multipart/form-data來區分請求是否爲文件上傳請求。其中boundary爲文件數據的分隔符,用於區分上傳多個文件。github
導入commons-fileupload.jar、commons-io.jar包。
一、界面
咱們就是須要一個form表單,爲其添加enctype屬性和post方法:web
<form action="${pageContext.request.contextPath}/servlet/UploadServlet2" method="post" enctype="multipart/form-data" >
姓名: <input type="text" name="name" /><br />
照片: <input type="file" name="photo" /><br />
<input type="submit" value="提交" />
</form>
二、邏輯處理
咱們在一個servlet中進行處理:sql
request.setCharacterEncoding("UTF-8");
//判斷用戶的請求內容是否是multipart/form-data
boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
throw new RuntimeException("error!");
}
//建立DiskFileItemFactory對象
DiskFileItemFactory factory=new DiskFileItemFactory();緩存
//建立核心解析類ServlertFileUpload
ServletFileUpload sfu=new ServletFileUpload(factory);
//解析請求對象
List<FileItem> items=new ArrayList<FileItem>(0);
try {
items=sfu.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(FileItem item:items){
if(item.isFormField()){
processFormField(item);
}else{
processUploadField(item);
}
}
response.getWriter().write("sucess!");
接下來就是分爲兩種狀況了,一種是對普通的表單元素進行處理,另外一種是對文件類的數據進行處理,對於第一種狀況的話就比較簡單,咱們直接獲取名字就能夠了,基本上不用過多的處理。服務器
private void processFormField(FileItem item) {
String fieldName=item.getFieldName();
String fieldValue=item.getString();
System.out.println(fieldValue+"="+fieldName);
}
對於第二種狀況,須要咱們直接對上傳文件進行一系列的處理了,咱們首先須要在服務器上找一個存放文件的地方,而後截取上傳的文件名、構建輸出流、關閉流等操做。
private void processUploadField(FileItem item) {
try {
InputStream in=item.getInputStream();
String filename=item.getName();
//在服務器上找一個存放文件的地方
String storeDirectoryRealPath=getServletContext().getRealPath("/WEB-INF/files");
File storeDirectory=new File(storeDirectoryRealPath);
if(!storeDirectory.exists()){
storeDirectory.mkdirs();
}
//截取上傳的文件名
//filename=filename.substring(filename.lastIndexOf(File.separator)+1);
if(filename!=null){
filename=FilenameUtils.getName(filename);
}
String guidFilename=GUIDUtil.generateGUID()+"_"+filename;
//按日期來區分存儲目錄
// String childDirectory=makeChileDirectory(storeDirectory);
String childDirectory=makeChildDirectory(storeDirectory,guidFilename);
//構建輸出流
OutputStream out=new FileOutputStream(new File(storeDirectory,childDirectory+File.separator+guidFilename));
int len = -1;
byte buf[] = new byte[1024];
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
一、把保存的文件放在用戶沒法直接訪問到的地方:例如放在:在WEB-INF/files目錄中。
String storeDirectoryRealPath=getServletContext().getRealPath("/WEB-INF/files");
二、讓文件名惟一。
String guidFilename=GUIDUtil.generateGUID()+"_"+filename;
//構建輸出流
OutputStream out=new FileOutputStream(new File(storeDirectory,guidFilename));
三、避免同一個文件夾中的文件過多。
3.1按照日期進行存儲。
String childDirectory=makeChileDirectory(storeDirectory);
private String makeChileDirectory(File storeDirectory) {
Date now=new Date();
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String sdate=df.format(now);
File f=new File(storeDirectory,sdate);
if(!f.exists()){
f.mkdirs();
}
return sdate;
}
3.2用文件名的hashCode計算須要進行存儲的目錄,二級目錄。
private String makeChildDirectory(File storeDirectory, String guidFilename) {
int hashCode = guidFilename.hashCode();
int dir1 = hashCode&0xf;// 0~15
int dir2 = (hashCode&0xf0)>>4;//0~15
String s = dir1+File.separator+dir2;
File f = new File(storeDirectory,s);
if(!f.exists()){
f.mkdirs();
}
return s;
}
四、限制文件的大小。web方式不適合上傳大的文件。
4.1單個文件大小:
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setFileSizeMax(4*1024*1024);//限制不超過4M
4.2總文件大小:多文件上傳
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setSizeMax(8*1024*1024);//總文件大小
五、限制文件的上傳類型。
5.1經過文件擴展名來進行限制。
String extensionName=FilenameUtils.getExtension(filename);
5.2經過文件MIME類型來限制。
String mimeType=item.getContentType();
六、空文件上傳解決方案。
判斷文件名是否爲空,當文件名爲空時return。
七、臨時文件
DiskFileItemFactory的做用是產生FileItem對象。其內部有一個緩存,默認大寫拾10kb,若是上傳文件超過10kb,則用磁盤做爲緩存。存放緩存的目錄默認是系統的臨時目錄。
DiskFileItemFactory factory=new DiskFileItemFactory();
//更改臨時文件的存放目錄
factory.setRepository(new File("D:/"));
若是是本身用IO流實現的文件上傳,則須要在流關閉後,清理臨時文件。
FileItem.delete();
可使用FileItem.write(File f)實現文件上傳的保存。
八、中文編碼
request.setCharacterEncoding("UTF-8");
//該編碼要和jsp頁面保持一致
String fieldValue=item.getString("UTF-8");
九、動態js控制上傳框
<form action="${pageContext.request.contextPath}/servlet/UploadServlet3" method="post" enctype="multipart/form-data">
name:<input type="text" name="name"/><br/>
<div id="d1">
<div>
photo:<input type="file" name="photo"/><input type="button" value="繼續上傳" onclick="addFile()"/>
</div>
</div>
<input type="submit" value="上傳"/>
</form>
<script type="text/javascript"> function addFile(){ var d1 = document.getElementById("d1"); var oldInnerHtml = d1.innerHTML; d1.innerHTML=oldInnerHtml+"<div>photo:<input type='file' name='photo'/><input type='button' value='刪除' onclick='deleteOne(this)'/></div>"; } function deleteOne(delBtn){ delBtn.parentNode.parentNode.removeChild(delBtn.parentNode); } </script>
首先咱們來看一下頁面的處理:
新建一個list.jsp文件:
所有資源以下:<br />
<c:forEach items="${map}" var="me">
<c:url value="/servlet/DownLoadServlet" var="url">
<c:param name="filename" value="${me.key}"></c:param>
</c:url>
${me.value} <a href="${url}">下載</a><br/>
</c:forEach>
要記得引入jstl的核心包 。
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
接下作界面顯示的servlet。
咱們以前上傳的文件是用GUID作過相應處理的,是一個拼接好的文件名,用來防止文件同名的狀況發生,這裏用戶瀏覽到的文件固然要和上傳的時候的文件名 相同,因此這裏咱們要進行截取,把GUID拼接的前綴去掉,以「_」分開。一個是在服務器中防同名的文件名以及顯示出來的截取後的文件名。這裏之前面說過的,防同名文件方法2:用文件名的hashCode計算須要進行存儲的目錄,二級目錄。這裏也就須要使用hashCode找到作過文件的路徑。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//key:GUID文件名 value:old文件名
Map<String, String> map = new HashMap<String, String>();
//獲取/WEB-INF/files的真實路徑
String rootDirectoryRealPath = getServletContext().getRealPath("/WEB-INF/files");
//遞歸遍歷找出全部的文件
System.out.println(rootDirectoryRealPath);
File rootDirectory = new File(rootDirectoryRealPath);
treeWalk(rootDirectory,map);
//存到請求範圍中,轉發給jsp顯示
request.setAttribute("map", map);
request.getRequestDispatcher("/list.jsp").forward(request, response);
}
//遞歸遍歷找出全部的文件,把文件名高出來
public void treeWalk(File file, Map<String, String> map) {
if(file.isFile()){
String guidFileName = file.getName();
String oldFileName = guidFileName.substring(guidFileName.indexOf("_")+1);
map.put(guidFileName, oldFileName);
}else{
//目錄
File[] childFiles = file.listFiles(); for(File f:childFiles){ treeWalk(f, map); } } }
接下來就是下載的處理了。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String guidFilename = request.getParameter("filename");//get方式提交的
guidFilename = new String(guidFilename.getBytes("ISO-8859-1"),"UTF-8");
//計算存放路徑
File storeDirectory = new File(getServletContext().getRealPath("/WEB-INF/files"));
String childDirectory = makeChildDirecotry(storeDirectory, guidFilename);// 13/1
//構建輸入流
InputStream in = new FileInputStream(new File(storeDirectory,childDirectory+File.separator+guidFilename));
//用響應對象的輸出流輸出:下載的方式
String oldFileName = guidFilename.substring(guidFilename.indexOf("_")+1);
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(oldFileName,"UTF-8"));//不適用火狐
response.setContentType("application/octet-stream");
OutputStream out = response.getOutputStream();
int len = -1;
byte buf[] = new byte[1024];
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
}
private String makeChildDirecotry(File storeDirectory, String guidFilename) {
int hashCode = guidFilename.hashCode();
int dir1 = hashCode&0xf;
int dir2 = (hashCode&0xf0)>>4;
String s = dir1+File.separator+dir2;
File f = new File(storeDirectory,s);
if(!f.exists()){
f.mkdirs();
}
return s;
}
經過這個網址進行訪問
http://localhost:8080/UploadDemo/servlet/ShowAllFilesServlet