本文实例为大家分享了javaweb文件下载的具体实现代码,供大家参考,具体内容如下
文件上传示例
注意:jsp页面编码为"UTF-8"
文件上传的必要条件
1.form表单,必须为POST方式提交
2.enctype="multipart/form-data"
3.必须有<input type="file" />
前端jsp页面
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
|
<%@ 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%>" rel="external nofollow" >
< title >My JSP 'index.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" rel="external nofollow" >
-->
</ head >
< script type = "text/javascript" >
function addFile(){
var div1=document.getElementById("div1");
div1.innerHTML+="< div >< input type = 'file' />< input type = 'button' value = '删除' onclick = 'deleteFile(this)' /> < br /></ div >";
}
function deleteFile(div){
//他的爷爷删除他的爸爸
div.parentNode.parentNode.removeChild(div.parentNode);
}
</ script >
< body >
< form action = "${pageContext.request.contextPath }/servlet/upLoadServlet" method = "post" enctype = "multipart/form-data" >
文件的描述:< input type = "text" name = "description" />< br />
< div id = "div1" >
< div >
< input type = "file" name = "file" />< input type = "button" value = "添加" onclick = "addFile()" />< br />
</ div >
</ div >
< input type = "submit" />
</ form >
</ 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
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
|
package com.learning.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
* Servlet implementation class UpLoadServlet
*/
@WebServlet ( "/servlet/upLoadServlet" )
public class UpLoadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//文件上传
//判断是否支持文件上传
boolean isMultipartContent = ServletFileUpload
.isMultipartContent(request);
if (!isMultipartContent) {
throw new RuntimeException( "不支持" );
}
// 创建一个DiskFileItemfactory工厂类
DiskFileItemFactory diskFileItemFactory= new DiskFileItemFactory();
// 创建一个ServletFileUpload核心对象
ServletFileUpload fileUpload= new ServletFileUpload(diskFileItemFactory);
//设置中文乱码
fileUpload.setHeaderEncoding( "UTF-8" );
//设置一个文件大小
fileUpload.setFileSizeMax( 1024 * 1024 * 3 ); //大小为3M
//设置总文件大小
//fileUpload.setSizeMax(1024*1024*10);//大小为10M
try {
//fileload解析request请求,返回list<FileItem>集合
List<FileItem> fileItems = fileUpload.parseRequest(request);
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {
//是文本域 (处理文本域的函数)
processFormField(fileItem);
} else {
//文件域 (处理文件域的函数)
processUpLoadField1(fileItem);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
/**
* @param fileItem
*
*/
private void processUpLoadField1(FileItem fileItem) {
try {
//获得文件读取流
InputStream inputStream = fileItem.getInputStream();
//获得文件名
String fileName = fileItem.getName();
//对文件名处理
if (fileName!= null ) {
fileName.substring(fileName.lastIndexOf(File.separator)+ 1 );
} else {
throw new RuntimeException( "文件名不存在" );
}
//对文件名重复处理
// fileName=new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
fileName=UUID.randomUUID()+ "_" +fileName;
//日期分类
SimpleDateFormat simpleDateFormat= new SimpleDateFormat( "yyyy-MM-dd" );
String date = simpleDateFormat.format( new Date());
//创建目录
File parent= new File( this .getServletContext().getRealPath( "/WEB-INF/upload/" +date));
if (!parent.exists()) {
parent.mkdirs();
}
//上传文件
fileItem.write( new File(parent, fileName));
//删除临时文件(如果上传文件过大,会产生.tmp的临时文件)
fileItem.delete();
} catch (IOException e) {
System.out.println( "上传失败" );
e.printStackTrace();
} catch (Exception e) {
}
}
/**
* @param fileItem
*/
//文件域
private void processUpLoadField(FileItem fileItem) {
try {
//获得文件输入流
InputStream inputStream = fileItem.getInputStream();
//获得是文件名字
String filename = fileItem.getName();
//对文件名字处理
if (filename!= null ) {
// filename.substring(filename.lastIndexOf(File.separator)+1);
filename = FilenameUtils.getName(filename);
}
//获得路径,创建目录来存放文件
String realPath = this .getServletContext().getRealPath( "/WEB-INF/load" );
File storeDirectory= new File(realPath); //既代表文件又代表目录
//创建指定目录
if (!storeDirectory.exists()) {
storeDirectory.mkdirs();
}
//防止文件名一样
filename=UUID.randomUUID()+ "_" +filename;
//目录打散 防止同一目录文件下文件太多,不好查找
//按照日期分类存放上传的文件
//storeDirectory = makeChildDirectory(storeDirectory);
//多级目录存放上传的文件
storeDirectory = makeChildDirectory(storeDirectory,filename);
FileOutputStream fileOutputStream= new FileOutputStream( new File(storeDirectory, filename));
//读取文件,输出到指定的目录中
int len= 1 ;
byte [] b= new byte [ 1024 ];
while ((len=inputStream.read(b))!=- 1 ){
fileOutputStream.write(b, 0 , len);
}
//关闭流
fileOutputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//按照日期来分类
private File makeChildDirectory(File storeDirectory) {
SimpleDateFormat simpleDateFormat= new SimpleDateFormat( "yyyy-MM-dd" );
String date = simpleDateFormat.format( new Date());
//创建目录
File childDirectory= new File(storeDirectory, date);
if (!childDirectory.exists()) {
childDirectory.mkdirs();
}
return childDirectory;
}
//多级目录
private File makeChildDirectory(File storeDirectory, String filename) {
filename=filename.replaceAll( "-" , "" );
File childDirectory = new File(storeDirectory, filename.charAt( 0 )+File.separator+filename.charAt( 1 ));
if (!childDirectory.exists()) {
childDirectory.mkdirs();
}
return childDirectory;
}
//文本域
private void processFormField(FileItem fileItem) {
//对于文本域的中文乱码,可以用new String()方式解决
try {
String fieldName = fileItem.getFieldName(); //表单中字段名name,如description
String fieldValue = fileItem.getString( "UTF-8" ); //description中value
// fieldValue=new String(fieldValue.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(fieldName + ":" +fieldValue);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。