文件上传首先要引入两个核心包
commons-fileupload-1.2.1.jar
commons-io-1.4.jar
下面是对文件上传和下载的一些代码做的一个简单封装,可以方便以后直接使用【使用时将封装好的jar包直接导入工程中即可使用】
上传文件核心代码
1 package com.lizhou.fileload;
2
3 import java.io.File;
4 java.io.FileOutputStream;
5 java.io.IOException;
6 java.io.InputStream;
7 java.io.OutputStream;
8 java.util.ArrayList;
9 java.util.List;
10 java.util.UUID;
11
12 javax.servlet.http.HttpServletRequest;
13
14 org.apache.commons.fileupload.FileItem;
15 org.apache.commons.fileupload.FileUploadException;
16 org.apache.commons.fileupload.disk.DiskFileItemFactory;
17 org.apache.commons.fileupload.servlet.ServletFileUpload;
18
19 com.lizhou.exception.FileFormatException;
20 com.lizhou.exception.NullFileException;
21 com.lizhou.exception.ProtocolException;
22 com.lizhou.exception.SizeException;
23
24 /**
25 * 上传文件
26 * @author bojiangzhou
27 *
28 */
29 public class FileUpload {
30 31 * 上传文件用的临时目录
32 33 private String tempPath = null;
34 35 * 上传文件用的文件目录
36 37 private String filePath = 38 39 * 内存中缓存区的大小,默认100k
40 41 private int bufferSize = 100 42 43 * 上传文件的最大大小,默认1M
44 45 int fileSize = 1000 46 47 * 上传文件使用的编码方式,默认UTF-8
48 49 private String encoding = "UTF-8" 50 51 * 上传文件的格式,默认无格式限制
52 53 private List<String> fileFormat = new ArrayList<String>();
54 55 * HttpServletRequest
56 57 private HttpServletRequest request;
58 //私有化无参构造
59 FileUpload(){}
60
61 public FileUpload(HttpServletRequest request){
62 this.request = request;
63 }
64
65 FileUpload(String tempPath,String filePath,HttpServletRequest request){
66 67 this.tempPath = tempPath;
68 this.filePath = filePath;
69 makeDirectory(tempPath);
70 makeDirectory(filePath);
71 72
73 74 * 上传文件
75 * @return 上传成功返回true
76 @throws ProtocolException
77 FileUploadException
78 NullFileException
79 SizeException
80 FileFormatException
81 IOException
82 83 boolean uploadFile()
84 throws ProtocolException,NullFileException,SizeException,FileFormatException,IOException,FileUploadException{
85 boolean b = true 86 ServletFileUpload upload = getUpload();
87 解析request中的字段,每个字段(上传字段和普通字段)都会自动包装到FileItem中
88 List<FileItem> fileItems = upload.parseRequest(this.request);
89 for(FileItem item : fileItems){
90 如果为普通字段
91 if(item.isFormField()){
92 continue 93 }
94 获取文件名
95 String fileName = item.getName();
96 因为IE6得到的是文件的全路径,所以进一步处理
97 fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
98 判断上传的文件是否为空
99 if(item.getSize() <= 0){
100 b = false101 throw new NullFileException();
102 103 判断文件是否超过限制的大小
104 if(item.getSize() > fileSize*1000105 b = 106 SizeException();
107 108 判断上传文件的格式是否正确
109 if( !isFormat(fileName.substring(fileName.lastIndexOf(".")+1)) ){
110 b = 111 FileFormatException();
112 113 String uuidFileName = getUuidFileName(fileName);
114 获取文件的输入流
115 InputStream is = item.getInputStream();
116 创建输出流
117 OutputStream os = new FileOutputStream(this.filePath+"/"+uuidFileName);
118 输出
119 output(is,os);
120 将上传文件时产生的临时文件删除
121 item.delete();
122 }
123 return b;
124 125
126 127 * 获取文件上传的输入流
128 @return
129 130 131 132 133 134 135 136 InputStream getUploadInputStream()
137 138 ServletFileUpload upload =139 140 List<FileItem> fileItems = upload.parseRequest(141 142 143 144 145 146 147 String fileName =148 149 fileName = fileName.substring(fileName.lastIndexOf("\\")+1150 151 152 153 154 155 156 157 158 159 160 161 162 163 InputStream is =164
165 is;
166 167 return 168 169
170 171 * 获取上传文件的核心
172 ServletFileUpload
173 ProtocolException
174 175 public ServletFileUpload getUpload() ProtocolException{
176 创建上传文件工厂
177 DiskFileItemFactory factory = DiskFileItemFactory();
178 设置内存中缓存区的大小
179 factory.setSizeThreshold(bufferSize);
180 如果用户未设置上传文件目录,则设置默认目录
181 if(filePath == 182 setDefaultFilePath();
183 184 如果用户未设置临时存放目录,则设置默认目录
185 if(tempPath == 186 setDefaultTempPath();
187 188 设置上传文件的的临时存放目录
189 factory.setRepository(new File(.tempPath));
190 创建上传文件对象[核心]
191 ServletFileUpload upload = ServletFileUpload(factory);
192 设置上传文件的编码方式
193 upload.setHeaderEncoding(.encoding);
194 /*
195 * 判断客户端上传文件是否使用MIME协议
196 * 只有当以MIME协议上传文件时,upload才能解析request中的字段
197 198 if(!upload.isMultipartContent(.request)){
199 ProtocolException();
200 201 upload;
202 203
204 205 * 输出
206 @param is
207 os
208 209 210 void output(InputStream is,OutputStream os) IOException{
211 byte[] by = new byte[1024];
212 int len = 0213 while( (len = is.read(by)) > 0 ){
214 os.write(by,0,len);
215 216 is.close();
217 os.close();
218 219
220 221 * 判断上传文件的格式是否正确
222 format 文件格式
223 boolean
224 225 isFormat(String format){
226 if(fileFormat.size() == 0227 228 229 (String f : fileFormat){
230 (f.equalsIgnoreCase(format)){
231 232 233 234 235 236
237 238 * 返回文件的UUID名,防止文件名重复
239 fileName 文件名
240 uuid名
241 242 String getUuidFileName(String fileName){
243 return UUID.randomUUID().toString()+"#"+fileName;
244 245
246 247 * 设置默认临时目录
248 249 void setDefaultTempPath(){
250 tempPath = filePath+"/temp"251
252 253 254
255 256 * 设置默认文件目录
257 * 默认在D盘
258 259 setDefaultFilePath(){
260 filePath = "D:/uploadFile"261
262 263 264
265 266 * 根据给定的文件目录创建目录
267 filePath
268 269 makeDirectory(String filePath){
270 File file = File(filePath);
271 if(!file.exists()){
272 file.mkdir();
273 274 275
276
277
278 279 * 获取临时目录
280 281 282 String getTempPath() {
283 284 285 286 * 设置临时目录
287 tempPath
288 289 setTempPath(String tempPath) {
290 291 292 293 294 * 获取文件路径
295 296 297 String getFilePath() {
298 299 300 301 * 返回文件路径
302 303 304 setFilePath(String filePath) {
305 306 307 308 309 * 获取内存中缓存区大小
310 311 312 int getBufferSize() {
313 bufferSize;
314 315 316 * 设置内存中缓存区大小
317 * 默认100k
318 bufferSize
319 320 void setBufferSize( bufferSize) {
321 this.bufferSize =322 323 324 * 获取上传文件的最大大小
325 326 327 getFileSize() {
328 fileSize;
329 330 331 * 限制上传文件的最大大小,单位为k
332 * 默认1000k
333 fileSize
334 335 void setFileSize( fileSize) {
336 this.fileSize =337 338 339 * 返回上传文件的编码方式
340 341 342 String getEncoding() {
343 encoding;
344 345 346 * 设置上传文件的编码方式
347 * 默认UTF-8格式
348 encoding
349 350 setEncoding(String encoding) {
351 this.encoding =352 353 354 * 获取允许上传文件的格式
355 356 357 String getFileFormat() {
358 359 return "*"360 361 String format = ""362 (String s:fileFormat){
363 format += ","+s;
364 365 format = format.substring(format.indexOf(",")+1366 format;
367 368 369 * 设置上传文件的格式,多个文件格式则多次调用该方法进行设置
370 fileFormat
371 372 setFileFormat(String format) {
373 .fileFormat.add(format);
374 375
376 HttpServletRequest getRequest() {
377 378 379
380 setRequest(HttpServletRequest request) {
381 382 383
384 }
下载文件核心代码
java.io.FileInputStream; java.io.FileNotFoundException; java.io.UnsupportedEncodingException; java.net.URLEncoder; 11 javax.servlet.http.HttpServletResponse; 16 com.lizhou.domain.DownloadFile; 18 com.lizhou.exception.FileNotExistsException; 19 * 下载文件 23 24 FileDownload { 26 * 下载时的默认文件目录 28 29 * 要下载文件的格式 38 39 FileDownload(HttpServletRequest request){ 40 41 42 43 FileDownload(String filePath,1)"> 44 45 46 47 48 49 * 将下载列表绑定到域中 50 * 默认session var 域对象变量名 52 FileNotExistsException 53 void bindDownloadFilesToScope(String var) FileNotExistsException{ 55 56 filePath = "D:/uploadFile" 57 58 if(!isFileExists(.filePath)){ 59 FileNotExistsException(); 60 61 List<DownloadFile> list = new ArrayList<DownloadFile> 62 getDownloadFiles(filePath,list); request.getSession().setAttribute(var,1)"> 64 65 66 67 * 获得下载目录下的所有文件 68 list 70 71 void getDownloadFiles(String filePath,List<DownloadFile> list){ 72 File file = 73 (file.isFile()){ 74 String uuidFileName = file.getName(); 75 if(isFormat(uuidFileName.substring(uuidFileName.lastIndexOf(".")+1))){ 76 DownloadFile df = DownloadFile(); 77 df.setFileName(uuidFileName.substring(uuidFileName.indexOf("#")+1)); df.setUuidFileName(uuidFileName); df.setFilePath(file.getPath()); list.add(df); 82 } else{ 83 File[] childFiles = file.listFiles(); (File cf : childFiles){ 85 getDownloadFiles(cf.getPath(),1)"> 86 87 88 89 90 91 * 下载文件 92 var 下载列表的域变量名 uuidFileName 客户端传来的文件的uuid名 94 response 95 96 97 void downloadFile(String var,String uuidFileName,HttpServletResponse response) 98 byte[] by = uuidFileName.getBytes("ISO-8859-1" 99 uuidFileName = new String(by,"UTF-8"100 List<DownloadFile> files = (List<DownloadFile>) .request.getSession().getAttribute(var); 101 (DownloadFile file : files){ 102 (file.getUuidFileName().equals(uuidFileName)){ 103 InputStream is = FileInputStream(file.getFilePath()); 104 OutputStream os = response.getOutputStream(); 105 response.setHeader("Content-Disposition","attachment; filename="+URLEncoder.encode(file.getFileName(),1)">106 output(is,1)">107 break108 109 110 111 112 113 114 115 116 os.write(by,1)">117 118 120 121 122 123 * 判断文件的格式是否正确 125 126 127 128 129 131 132 133 135 136 137 138 139 140 * 判断文件目录是否存在 141 filePath 文件目录 142 143 144 isFileExists(String filePath){ 145 146 File file = 147 148 b = 149 150 151 152 153 154 155 156 157 158 * 设置下载路径 159 160 FileNotExistsException 161 162 163 164 165 166 167 169 171 172 174 String format = ""175 176 format += ",1)">177 178 format = format.substring(format.indexOf(",1)">179 180 181 184 185 186 188 189 191 192 193 196 197 }
注:上传文件时,前台form表单一定要有如下属性:enctype="multipart/form-data"
附上源码+导出的jar包+使用demo:下载文件
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。