您當前位置>首頁 » 新聞資(zī)訊 » 網站(zhàn)建設 >
Java web開發——文(wén)件的上傳和(hé)下(xià)載
發表時間:2018-7-28
發布人:葵宇科技
浏覽次數:30
打個(gè)廣告,幫朋友賣點東西,東西超便宜的喲【衣服鞋子(zǐ)等】,廠家直接出貨,絕對低于市場價!!! 一般都比市場價便宜3—7折【都是牌子(zǐ)貨】,如(rú)果您感興趣,可(kě)以掃描屏幕下(xià)方的二維碼,感謝關(guān)注!!!
一、文(wén)件上傳
1、概述
實現web開發中(zhōng)的文(wén)件上傳功能,需完成如(rú)下(xià)二步操作:
- 在web頁面中(zhōng)添加上傳輸入項
- 在servlet中(zhōng)讀取上傳文(wén)件的數據,并保存到本地硬盤中(zhōng)。
2、在web頁面中(zhōng)
在web頁面中(zhōng)通(tōng)過<input type=“file”>标簽添加上傳輸入項,設置文(wén)件上傳輸入項時須注意:
1、必須要設置input輸入項的name屬性,否則浏覽器(qì)将不會發送上傳文(wén)件的數據。
2、必須把form的enctype屬值設為multipart/form-data.設置該值後,浏覽器(qì)在上傳文(wén)件時,将把文(wén)件數據附帶在http請求消息體中(zhōng),并使用MIME協議對上傳的文(wén)件進行描述,以方便接收方對上傳數據進行解析和(hé)處理。
<form action="${pageContext.request.contextPath }/servlet/UploadServlet3" enctype="multipart/form-data" method="post">
上傳用戶:<input type="text" name="username"><br/>
上傳文(wén)件1:<input type="file" name="file1"><br/>
上傳文(wén)件2:<input type="file" name="file2"><br/>
<input type="submit" value="提交">
</form>
注意:如(rú)果要動(dòng)态添加上傳輸入項可(kě)以:
<html>
<head>
<title>My JSP 'upload2.jsp' starting page</title>
<script type="text/javascript">
function addinput(){
var div = document.getElementById("file");
var input = document.createElement("input");
input.type="file";
input.name="filename";
var del = document.createElement("input");
del.type="button";
del.value="删除";
del.onclick = function d(){
this.parentNode.parentNode.removeChild(this.parentNode);
}
var innerdiv = document.createElement("div");
innerdiv.appendChild(input);
innerdiv.appendChild(del);
div.appendChild(innerdiv);
}
</script>
</head>
<body>
<form action="" enctype="mutlipart/form-data"></form>
<table>
<tr>
<td>上傳用戶:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>上傳文(wén)件:</td>
<td>
<input type="button" value="添加上傳文(wén)件" class="has" src="https://img-blog.csdn.net/20180728200740972?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzIyMTcyMTMz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" />
3、在Servlet中(zhōng)
1.基本介紹
在Servlet中(zhōng)通(tōng)過開源組件( Commons-fileupload )讀取文(wén)件上傳數據,并保存到本地硬盤中(zhōng)。使用Commons-fileupload組件實現文(wén)件上傳,需要導入該組件相應的支撐jar包:
Commons-fileupload和(hé)commons-io
注意:如(rú)果表單的提交類型為multipart/form-data的話,在servlet方就不能采用傳統方式獲取表單數據
String username = request.getParameter("username");
System.out.println(username);
2.相關(guān)方法
1.DiskFileItemFactory
DiskFileItemFactory 是創建 FileItem 對象的工廠,這個(gè)工廠類常用方法:
方法介紹public void setSizeThreshold(int sizeThreshold) 設置内存緩沖區的大小,默認值為10K。當上傳文(wén)件大于緩沖區大小時, fileupload組件将使用臨時文(wén)件緩存上傳文(wén)件。public void setRepository(java.io.File repository) 指定臨時文(wén)件目錄,默認值為System.getProperty("java.io.tmpdir").public DiskFileItemFactory(int sizeThreshold, java.io.File repository) 構造函數
2.ServletFileUpload
負責處理上傳的文(wén)件數據,并将表單中(zhōng)每個(gè)輸入項封裝成一個(gè) FileItem 對象中(zhōng)。常用方法有:
方法介紹boolean isMultipartContent(HttpServletRequest request) 判斷上傳表單是否為multipart/form-data類型List parseRequest(HttpServletRequest request)解析request對象,并把表單中(zhōng)的每一個(gè)輸入項包裝成一個(gè)fileItem 對象,并返回一個(gè)保存了所有FileItem的list集合。setFileSizeMax(long fileSizeMax) 設置上傳文(wén)件的最大值setSizeMax(long sizeMax) 設置上傳文(wén)件總量的最大值setHeaderEncoding(java.lang.String encoding) 設置編碼格式setProgressListener(ProgressListener pListener) 上傳監聽器(qì),可(kě)以知道文(wén)件上傳進度
3.servlet實現
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
?
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
?
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
?
public class UploadServlet2 extends HttpServlet {
?
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
//1.得到解析器(qì)工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//設置緩存文(wén)件路(lù)徑(臨時文(wén)件)
factory.setRepository(new File(this.getServletContext().getRealPath("/WEB-INF/temp")));
//2.得到解析器(qì)
ServletFileUpload upload = new ServletFileUpload(factory);
?
upload.setHeaderEncoding("UTF-8"); //解決上傳文(wén)件名的中(zhōng)文(wén)亂碼
//3.判斷上傳表單的類型
if(!upload.isMultipartContent(request)){
//上傳表單為普通(tōng)表單,則按照傳統方式獲取數據即可(kě)
return;
}
//為上傳表單,則調用解析器(qì)解析上傳數據
List<FileItem> list = upload.parseRequest(request); //FileItem
//遍曆list,得到用于封裝第一個(gè)上傳輸入項數據fileItem對象
for(FileItem item : list){
if(item.isFormField()){
//得到的是普通(tōng)輸入項
String name = item.getFieldName(); //得到輸入項的名稱
String value = item.getString("UTF-8");//或者String value = item.getString();加下(xià)
//value = new String(value.getBytes("iso8859-1"),"UTF-8");
System.out.println(name + "=" + value);
}else{
//得到上傳輸入項
String filename = item.getName(); //得到上傳文(wén)件名 C:\Documents and Settings\ThinkPad\桌面\1.txt(有些浏覽器(qì))||1.txt
if(filename==null || filename.trim().equals("")){//如(rú)果上傳輸入框為空,跳出
continue;
}
filename = filename.substring(filename.lastIndexOf("\\")+1);
InputStream in = item.getInputStream(); //得到上傳數據
int len = 0;
byte buffer[]= new byte[1024];
String savepath = this.getServletContext().getRealPath("/upload");
FileOutputStream out = new FileOutputStream(savepath + "\\" + filename); //向upload目錄中(zhōng)寫入文(wén)件
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
out.close();
item.delete();//删除臨時文(wén)件
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
?
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
?
doGet(request, response);
}
?
}
注意:
1.上傳的文(wén)件一般禁止别人訪問(wèn),故可(kě)以放在WEB-INF目錄下(xià)
//用于保存上傳文(wén)件的目錄應該禁止外界直接訪問(wèn)
String savepath = this.getServletContext().getRealPath("/WEB-INF/upload");
System.out.println(savepath);
2.為了防止上傳名稱相同的文(wén)件,可(kě)以使用UUID
String savepath = this.getServletContext().getRealPath("/upload");
String saveFilename = makeFileName(filename); //得到文(wén)件保存的名稱
FileOutputStream out = new FileOutputStream(savepath + "\\" + saveFilename); //向upload目錄中(zhōng)寫入文(wén)件
。。。。。。。。。。。。。。。
?
public String makeFileName(String filename){ //2.jpg
return UUID.randomUUID().toString() + "_" + filename;
}
3.防止一個(gè)文(wén)件夾下(xià)的文(wén)件太多(文(wén)件夾下(xià)文(wén)件過多,将導緻打開緩慢)
String savepath = this.getServletContext().getRealPath("/upload");
String realSavePath = makePath(filename, savePath); //得到文(wén)件的保存目錄
FileOutputStream out = new FileOutputStream(realSavePath + "\\" + filename);
?
public String makePath(String filename,String savePath){//文(wén)件的存放位置是根據文(wén)件名算出的,以後再下(xià)載的時候可(kě)以根據計算結果來确定文(wén)件存放的地址
int hashcode = filename.hashCode();//拿到filename的地址
int dir1 = hashcode&0xf; //0--15,拿到低四位當一級目錄
int dir2 = (hashcode&0xf0)>>4; //0-15,5到8位當二級目錄
String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
File file = new File(dir);
if(!file.exists()){//如(rú)果這個(gè)目錄不存在,創建
file.mkdirs();
}
return dir;
}
4.限制上傳文(wén)件的大小
upload.setFileSizeMax(1024);//單個(gè)文(wén)件不能超過1k
upload.setSizeMax(1024*10);//總共不能超過10k
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
?
?
}catch (FileUploadBase.FileSizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("message", "文(wén)件超出最大值!!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
5.監聽文(wén)件上傳進度
//2.得到解析器(qì)
ServletFileUpload upload = new ServletFileUpload(factory);
?
upload.setProgressListener(new ProgressListener(){
public void update(long pBytesRead, long pContentLength, int arg2) {
System.out.println("文(wén)件大小為:" + pContentLength + ",當前已處理:" + pBytesRead);
}
});
?
upload.setHeaderEncoding("UTF-8"); //解決上傳文(wén)件名的中(zhōng)文(wén)亂碼
二、文(wén)件下(xià)載
文(wén)件下(xià)載列表:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
?
<c:forEach var="me" items="${map}">
<c:url value="/servlet/DownLoadServlet" var="downurl">
<c:param name="filename" value="${me.key}"></c:param>
</c:url>
${me.value } <a href="${downurl}">下(xià)載</a> <br/>
</c:forEach>
</body>
</html>
查找所有文(wén)件:
//列出網站(zhàn)所有下(xià)載文(wén)件
public class ListFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filepath = this.getServletContext().getRealPath("/WEB-INF/upload");
Map map = new HashMap();
listfile(new File(filepath),map);
request.setAttribute("map", map);
request.getRequestDispatcher("/listfile.jsp").forward(request, response);
}
public void listfile(File file,Map map){
if(!file.isFile()){//如(rú)果不是文(wén)件,是文(wén)件夾
File files[] = file.listFiles();
for(File f : files){
listfile(f,map);
}
}else{
String realname = file.getName().substring(file.getName().indexOf("_")+1); //9349249849-88343-8344_阿_凡_達.avi
map.put(file.getName(), realname);//UUID,文(wén)件名
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
通(tōng)過傳過來的參數(文(wén)件名的UUID)來算出文(wén)件所在文(wén)件夾,并将其取出
public class DownLoadServlet extends HttpServlet {
?
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
?
String filename = request.getParameter("filename"); //23239283-92489-阿凡達.avi
filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
String path = makePath(filename,this.getServletContext().getRealPath("/WEB-INF/upload"));
File file = new File(path + "\\" + filename);
if(!file.exists()){
request.setAttribute("message", "您要下(xià)載的資(zī)源已被删除!!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
String realname = filename.substring(filename.indexOf("_")+1);
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
FileInputStream in = new FileInputStream(path + "\\" + filename);
OutputStream out = response.getOutputStream();
byte buffer[] = new byte[1024];
int len = 0;
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
out.close();
}
public String makePath(String filename,String savePath){
int hashcode = filename.hashCode();