本文實例講述了java文件上傳與文件下載實現方法。分享給大家供大家參考,具體如下:
java文件上傳
數據上傳是客戶端向服務器端上傳數據,客戶端向服務器發送的所有請求都屬于數據上傳。文件上傳是數據上傳的一種特例,指客戶端向服務器上傳文件。即將保存在客戶端的文件上傳一個副本到服務器,并保存在服務器中。
1、上傳表單要求
-
文件上傳要求客戶端提交特殊的請求——multipart請求,即包含多部分數據的請求。必須將<form/>標簽的enctype屬性值設為“
multipart/form-data
”,enctype表示encodingtype,及編碼類型 - 由于客戶端上傳文件的大小是不確定的,所以http協議規定,文件上傳的數據要存放于請求正文中,不能出現在url地址欄內。也就是說,想要上傳文件必須提交post請求。
-
表單中要有
<input type="file" />
標簽 -
注意:
multipart/form-data
請求與普通請求不同
2、下載文件上傳jar包并查看官方文檔
打開apache官網http://www.apache.org/,選擇apache project list中的commons
選擇commons中的fileupload項目,并下載jar包和源文件
查看fileupload的工作方式
查看fileupload項目的api
3、使用第三方jar包上傳文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
public class registerservlet extends httpservlet { private static final long serialversionuid = 1l; public registerservlet() { super (); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { response.getwriter().append( "served at: " ).append(request.getcontextpath()); } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //第一步、判斷請求是否為multipart請求 if (!servletfileupload.ismultipartcontent(request)) { throw new runtimeexception( "當前請求只支持文件上傳" ); } try { //第二步、創建fileitem工廠 diskfileitemfactory factory = new diskfileitemfactory(); //設置臨時文件存儲目錄 string path = this .getservletcontext().getrealpath( "/temp" ); file temp = new file(path); factory.setrepository(temp); //單位:字節。本例設置邊界值為2mb,超過該值會創建臨時文件 factory.setsizethreshold( 1024 * 1024 * 2 ); //第三步、創建文件上傳核心組件 servletfileupload upload = new servletfileupload(factory); //設置item的頭部字符編碼,解決中文亂碼問題 upload.setheaderencoding( "utf-8" ); //設置單個上傳文件的最大值為5mb upload.setfilesizemax( 1024 * 1024 * 5 ); //設置一次上傳所有文件總和的最大值為10mb(上傳多個文件時起作用) upload.setfilesizemax( 1024 * 1024 * 10 ); //第四步、解析請求獲取所有的item list<fileitem> items = upload.parserequest(request); //第五步、遍歷item for (fileitem item:items) { if (item.isformfield()) { processformfield(item); } else { processuploadedfile(item); } } } catch (fileuploadexception e) { e.printstacktrace(); } } private void processformfield(fileitem item) { try { string name = item.getfieldname(); //解決中文亂碼問題 string value = item.getstring( "utf-8" ); system.out.println(name+ "=" +value); } catch (unsupportedencodingexception e) { e.printstacktrace(); } } private void processuploadedfile(fileitem item) { try { inputstream inputstream = item.getinputstream(); string fieldname = item.getfieldname(); //獲取上傳文件原始名稱 string filename = item.getname(); //解決文件同名問題 filename = system.currenttimemillis()+filename; string contenttype = item.getcontenttype(); boolean isinmemory = item.isinmemory(); long sizeinbytes = item.getsize(); string path = this .getservletcontext().getrealpath( "/uploadcontent" ); //date now = new date(); calendar now = calendar.getinstance(); //對上傳的文件進行分類管理 path += "/" +now.get(calendar.year)+ "/" +(now.get(calendar.month)+ 1 )+ "/" +now.get(calendar.day_of_month); //若目錄不存在,則創建該目錄 file directory = new file(path); if (!directory.exists()) { directory.mkdirs(); } file descfile = new file(path,filename); outputstream outputstream = new fileoutputstream(descfile); int length = - 1 ; byte [] buffer = new byte [ 1024 ]; while ((length=inputstream.read(buffer))!=- 1 ) { outputstream.write(buffer, 0 , length); } outputstream.close(); inputstream.close(); //刪除臨時文件 item.delete(); } catch (ioexception e) { e.printstacktrace(); } } } |
java文件下載
數據下載是客戶端從服務器獲取數據,服務器向客戶端發送的所有響應都屬于數據下載。文件下載是數據下載的一種特例,指客戶端從服務器下載文件,即將保存在服務器的文件下載一個副本到客戶端。通常我們對服務器所發出的請求,大多是文件下載請求,從服務器中下載文本、圖片、聲音、視頻等文件,客戶端瀏覽器對這些文件進行解析后,我們才能看到多媒體信息。
1、超鏈接下載
- 瀏覽器能解析的文件會直接顯示,如:pdf、jpg......
- 瀏覽器解析不了的文件會被另存為,如:rar、exe......
- 瀏覽器版本不一樣,對文件的解析能力也不同
- 缺點:下載內容的形式(直接顯示/另存為)由瀏覽器決定,跟服務器無關
2、servlet方式下載
- 設置響應頭部屬性content-disposition值為attachment
- 獲取連接服務器源文件的輸入流
- 獲取輸出流
- 將輸入流中的數據寫到輸出流中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
public class downloadservlet extends httpservlet { private static final long serialversionuid = 1l; public downloadservlet() { super (); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //設置響應的頭部屬性content-disposition值為attachment //使用filename來指定文件名 string filename = "超跑.png" ; byte [] bytes = filename.getbytes( "utf-8" ); //http協議規定瀏覽器只能接受iso8859-1類型的字節數據 filename = new string(bytes, "iso8859-1" ); response.setheader( "content-disposition" , "attachment;filename=" +filename); //獲取連接服務器資源文件的輸入流 inputstream is = request.getservletcontext().getresourceasstream( "/resources/bs架構原理圖1.png" ); //獲取輸出流 servletoutputstream os = response.getoutputstream(); //將輸入流中的數據寫到輸出流中 int length = - 1 ; byte [] buffer = new byte [ 1024 ]; while ((length=is.read(buffer))!=- 1 ) { os.write(buffer, 0 ,length); } os.close(); is.close(); } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } } |
希望本文所述對大家java程序設計有所幫助。
原文鏈接:https://blog.csdn.net/xiaouncle/article/details/80379322