一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專(zhuān)注于服務(wù)器技術(shù)及軟件下載分享
分類(lèi)導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語(yǔ)言 - JAVA教程 - JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載實(shí)例解析

JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載實(shí)例解析

2020-03-25 13:51森林森 JAVA教程

這篇文章主要介紹了JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載的相關(guān)資料,需要的朋友可以參考下

首先給大家介紹一文件的上傳

實(shí)體類(lèi)

?
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
import java.sql.Timestamp;
/**
*
* @Decription 文件上傳實(shí)體類(lèi)
*
*/
public class Upfile {
private String id;// ID主鍵 使用uuid隨機(jī)生成
private String uuidname; // UUID名稱(chēng)
private String filename;//文件名稱(chēng)
private String savepath; // 保存路徑
private Timestamp uploadtime; // 上傳時(shí)間
private String description;// 文件描述
private String username; // 用戶(hù)名
public Upfile() {
super();
}
public Upfile(String id, String uuidname, String filename, String savepath,
Timestamp uploadtime, String description, String username) {
super();
this.id = id;
this.uuidname = uuidname;
this.filename = filename;
this.savepath = savepath;
this.uploadtime = uploadtime;
this.description = description;
this.username = username;
}
public String getDescription() {
return description;
}
public String getFilename() {
return filename;
}
public String getId() {
return id;
}
public String getSavepath() {
return savepath;
}
public Timestamp getUploadtime() {
return uploadtime;
}
public String getUsername() {
return username;
}
public String getUuidname() {
return uuidname;
}
public void setDescription(String description) {
this.description = description;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setId(String id) {
this.id = id;
}
public void setSavepath(String savepath) {
this.savepath = savepath;
}
public void setUploadtime(Timestamp uploadtime) {
this.uploadtime = uploadtime;
}
public void setUsername(String username) {
this.username = username;
}
public void setUuidname(String uuidname) {
this.uuidname = uuidname;
}
}

頁(yè)面

?
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
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'upload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>文件上傳</h1>
<form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
<table>
<tr>
<td> 上傳用戶(hù)名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td> 上傳文件:</td>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td> 描述:</td>
<td><textarea rows="5" cols="50" name="description"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="上傳開(kāi)始"/></td>
</tr>
</table>
</form>
<div>${msg }</div>
<a href="${pageContext.request.contextPath }/index.jsp">返回主頁(yè)</a>
</body>
</html>

Servlet

?
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
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.itheima.domain.Upfile;
import com.itheima.exception.MyException;
import com.itheima.service.UpfileService;
import com.itheima.service.impl.UpfileServiceImpl;
import com.itheima.untils.WebUntil;
public class UploadFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//判斷表單是不是多個(gè)部分組成的
if(!ServletFileUpload.isMultipartContent(request)){
request.setAttribute("msg", "表單個(gè)設(shè)置錯(cuò)誤,請(qǐng)檢查enctype屬性是是否設(shè)置正確");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
}
//是多部分組成的就獲取并遍歷返回一個(gè)文件上傳對(duì)象,包含上傳的所有信息
try {
Upfile upfile=WebUntil.upload(request);
UpfileService upfileService=new UpfileServiceImpl();
boolean flag=upfileService.add(upfile);
if(flag){
request.setAttribute("msg", "上傳成功");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
}else{
request.setAttribute("msg", "上傳失敗,請(qǐng)重試");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
}
}catch (FileSizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("msg", "單個(gè)文件大小 ,超過(guò)最大限制");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
} catch (SizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("msg", "總文件大小 ,超過(guò)最大限制");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
}
}
}

工具類(lèi)

?
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.itheima.domain.Upfile;
import com.itheima.exception.MyException;
/**
* 文件上傳工具類(lèi)
* @Decription TODO
*
*/
public class WebUntil {
/**
* 文件上傳的方法
* @param request 請(qǐng)求參數(shù)傳入
* @return 返回一個(gè)Upfile對(duì)象
* @throws FileSizeLimitExceededException
* @throws SizeLimitExceededException
* @throws IOException
*/
public static Upfile upload(HttpServletRequest request) throws FileSizeLimitExceededException, SizeLimitExceededException {
Upfile upfile=new Upfile();
ArrayList<String> fileList=initList();
try {
//獲取磁盤(pán)文件對(duì)象工廠
DiskFileItemFactory factory=new DiskFileItemFactory();
String tmp=request.getSession().getServletContext().getRealPath("/tmp");
System.out.println(tmp);
//初始化工廠
setFactory(factory,tmp);
//獲取文件上傳解析器
ServletFileUpload upload=new ServletFileUpload(factory);
//初始化解析器
setUpload(upload);
//獲取文件列表集合
List<FileItem> list = upload.parseRequest(request);
//遍歷
for (FileItem items : list) {
//判斷 是不是普通表單個(gè)對(duì)象
if(items.isFormField()){
//獲取上傳表單的name
String fieldName=items.getFieldName();
//value
String fieldValue=items.getString("UTF-8");
//判斷
if("username".equals(fieldName)){
//設(shè)置
upfile.setUsername(fieldValue);
}else if("description".equals(fieldName)){
//設(shè)置屬性
upfile.setDescription(fieldValue);
}
}else{
//是文件就準(zhǔn)備上傳
//獲取文件名
String filename=items.getName();
//處理因?yàn)闉g覽器不同而導(dǎo)致的 獲得 的 文件名的 差異
int index=filename.lastIndexOf("\\");
if(index!=-1){
filename=filename.substring(index+1);
}
//生成隨機(jī)的文件名
String uuidname=generateFilename(filename);
//獲取上傳的文件路徑
String savepath=request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
//獲取請(qǐng)求對(duì)象中的輸入流
InputStream in = items.getInputStream();
//將文件打散存放在不同的路徑,求出路徑
savepath=generateRandomDir(savepath,uuidname);
//復(fù)制文件
uploadFile(in,savepath,uuidname);
String id=UUID.randomUUID().toString();
upfile.setId(id);
upfile.setSavepath(savepath);
upfile.setUuidname(uuidname);
upfile.setFilename(filename);
//清除緩存
items.delete();
}
}
}catch ( FileUploadBase.FileSizeLimitExceededException e) {
//拋出出異常
throw e;
} catch (FileUploadBase.SizeLimitExceededException e) {
//拋出出異常
throw e;
}catch (FileUploadException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return upfile;
}
/**
* 初始化文件列表
* @return
*/
private static ArrayList<String> initList() {
ArrayList<String> list=new ArrayList<String>();
list.add(".jpg");
list.add(".rar");
list.add(".txt");
list.add(".png");
return list;
}
/**
* 復(fù)制文件
* @param in items中的輸入流
* @param savepath 保存路徑
* @param uuidname 文件名
*/
private static void uploadFile(InputStream in, String savepath,
String uuidname) {
//獲取文件
File file=new File(savepath, uuidname);
OutputStream out = null;
try {
int len=0;
byte [] buf=new byte[1024];
//獲取輸出流
out = new FileOutputStream(file);
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 生成隨機(jī)的存放路徑
* @param savepath 保存路徑
* @param uuidname 生成的uuid名稱(chēng)
* @return
* 使用hashcode完成
*/
private static String generateRandomDir(String savepath, String uuidname) {
//轉(zhuǎn)化為hashcode
System.out.println("上傳路徑"+savepath);
System.out.println("UUIDNAME"+uuidname);
int hashcode=uuidname.hashCode();
//容器
StringBuilder sb=new StringBuilder();
while(hashcode>0){
//與上15
int tmp=hashcode&0xf;
sb.append("/");
sb.append(tmp+"");
hashcode=hashcode>>4;
}
//拼接新的路徑
String path=savepath+sb.toString();
System.out.println("path"+path);
File file=new File(path);
//判斷路徑存不存在
if(!file.exists()){
//不存在就創(chuàng)建
file.mkdirs();
}
//返回保存路徑
return path;
}
/**
* 生成新的文件名
* @param uuidname 隨機(jī)的ID名字
* @param filename 原來(lái)的名
* @return
*/
private static String generateFilename( String filename) {
String uuidname=UUID.randomUUID().toString();
return uuidname.replace("-", "").toString()+"_"+filename;
}
/**
* 初始化解析器
* @param upload
*/
private static void setUpload(ServletFileUpload upload) {
// 設(shè)置 字符編碼
upload.setHeaderEncoding("utf-8");
//設(shè)置文件大小
upload.setFileSizeMax(1024*1024*20);
//設(shè)置總文件大小
upload.setSizeMax(1024*1024*50);
//設(shè)置進(jìn)度監(jiān)聽(tīng)器
upload.setProgressListener(new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("已經(jīng)讀取: "+pBytesRead+",總共有: "+pContentLength+", 第"+pItems+"個(gè)");
}
});
}
/**
* 工廠初始化方法
* @param factory
* @param tmp 緩沖目錄
*/
private static void setFactory(DiskFileItemFactory factory, String tmp) {
/// 配置初始化值緩沖區(qū)
factory.setSizeThreshold(1024*1024);
File file=new File(tmp);
//設(shè)置緩沖目錄
factory.setRepository(file);
}
}

二文件下載

Servlet

?
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
public class DownupfileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//獲取ID
String id=request.getParameter("id");
//業(yè)務(wù)層的接口
UpfileService upfileService=new UpfileServiceImpl();
//根據(jù)ID查找這個(gè)對(duì)象
Upfile upfile=upfileService.findUpfileById(id);
if(upfile==null){
return;
}
//獲取文件的真實(shí)名稱(chēng)
String filename=upfile.getFilename();
//如果文件名中有中文,需要轉(zhuǎn)碼,不然就下載時(shí)沒(méi)有文件名
filename=URLEncoder.encode(filename, "utf-8");
//更改過(guò)的名稱(chēng)
String uuidname=upfile.getUuidname();
//保存路徑
String savepath=upfile.getSavepath();
File file=new File(savepath,uuidname);
//判斷文件 是否存在
if(!file.exists()){
request.setAttribute("msg", "下載 的文件過(guò)期了");
request.getRequestDispatcher("/index").forward(request, response);
return;
}
//設(shè)置文件下載響應(yīng)頭信息
response.setHeader("Content-disposition", "attachement;filename="+filename);
//使用IO流輸出
InputStream in = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
int len=0;
byte [] buf=new byte[1024];
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
}
}

數(shù)據(jù)庫(kù)

?
1
2
3
4
5
6
7
8
9
10
11
create database upload_download_exercise;
use upload_download_exercise;
create table upfiles(
id varchar(100), //使用UUID生成
uuidname varchar(255),//uuid加上原來(lái)的文件名
filename varchar(100),//真實(shí)文件名
savepath varchar(255),//保存路徑
uploadtime timestamp,//上傳時(shí)間
description varchar(255),//描述
username varchar(10) 上傳人
);

以上所述是小編給大家分享的JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載的相關(guān)內(nèi)容,希望對(duì)大家有所幫助。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 美女任你模 | 免费视频一区二区 | 毛片大全免费看 | 好爽视频 | 日韩精品中文字幕视频一区 | 国产福利一区二区在线精品 | 久久机热免费视频 | 韩国靠逼 | 国产一区二区精品久久 | 亚洲精品视 | 久久视频在线视频观看天天看视频 | 国产免费一区二区 | 日本人交换乱理伦片 | 亚洲视频在线观看免费 | 果冻传媒mv在线观看入口免费 | 美国复古性经典xxxxx | 天堂中文在线免费观看 | 亚洲国产精品成人综合久久久 | 国产一级黄色录像 | 45分钟做受片免费观看 | 国产在线拍 | 亚洲精品久久啪啪网站成年 | 99视频都是精品热在线播放 | 明星ai人脸替换造梦在线播放 | 国产成人+亚洲欧洲 | 调教车文| 欧美精品日韩 | 美女视频ww8888网网 | 帅老头恋帅老头同性tv | 国产一区国产二区国产三区 | 免费看男女污污完整版 | 本土自拍 | 欧美性野久久久久久久久 | 国产高清自拍视频 | 俄罗斯女人与公拘i交酡 | 亚洲欧美自偷自拍另类小说 | 我和么公的秘密小说免费 | 亚洲天堂2015 | 国产区成人精品视频 | 精品国产一区二区三区在线 | 九九免费精品视频 |