您的位置:首页 > 编程语言 > Java开发

Java文件上传组件 common-fileUpload 使用教程

2013-07-30 09:31 579 查看
最近项目中,在发布商品的时候要用到商品图片上传功能(网站前台和后台都要用到),所以单独抽出一个项目来供其他的项目进行调用 ,对外透露的接口的为两个servlet供外部上传和删除图片,利用到连个jarcommons-fileupload-1.2.1.jar,commons-io-1.4.jar

项目结构如下:



其中com.file.helper主要提供读相关配置文件的帮助类

com.file.servlet 是对外提供调用上传和删除的图片的servlet

com.file.upload 是主要提供用于上传和删除图片的接口

1、FileConst类主要是用读取文件存储路径和设置文件缓存目录 允许上传图片的最大值

01
package
com.file.helper;
02
 
03
import
java.io.IOException;
04
import
java.util.Properties;
05
 
06
public
class

FileConst {
07
 
08
    
private

static
Properties properties=

new
Properties();
09
    
static
{
10
        
try

{
11
            
properties.load(ReadUploadFileType.
class
.getClassLoader().getResourceAsStream(
"uploadConst.properties"
));
12
        
}

catch
(IOException e) {
13
            
e.printStackTrace();
14
        
}
15
    
}
16
    
 
17
    
public

static
String getValue(String key){
18
        
String value = (String)properties.get(key);
19
        
return

value.trim();
20
    
}
21
}
2、ReadUploadFileType读取允许上传图片的类型和判断上传的文件是否符合约束的文件类型

01
package
com.file.helper;
02
 
03
import
java.io.File;
04
import
java.io.IOException;
05
import
java.util.ArrayList;
06
import
java.util.List;
07
import
java.util.Properties;
08
 
09
import
javax.activation.MimetypesFileTypeMap;
10
 
11
 
12
 
13
/**
14
 
* 读取配置文件
15
 
* @author Owner
16
 
*
17
 
*/
18
public
class

ReadUploadFileType {
19
 
20
    
 
21
    
private

static
Properties properties=

new
Properties();
22
    
static
{
23
        
try

{
24
            
properties.load(ReadUploadFileType.
class
.getClassLoader().getResourceAsStream(
"allow_upload_file_type.properties"
));
25
        
}

catch
(IOException e) {
26
            
e.printStackTrace();
27
        
}
28
        
 
29
    
}
30
    
/**
31
     
* 判断该文件是否为上传的文件类型
32
     
* @param uploadfile
33
     
* @return
34
     
*/
35
    
public

static
Boolean readUploadFileType(File uploadfile){
36
        
if
(uploadfile!=
null
&&uploadfile.length()>
0
){
37
            
String ext = uploadfile.getName().substring(uploadfile.getName().lastIndexOf(
"."
)+
1
).toLowerCase();
38
            
List<String>allowfiletype =
new
ArrayList<String>();
39
            
for
(Object key : properties.keySet()){
40
                
String value = (String)properties.get(key);
41
                
String[] values = value.split(
","
);
42
                
for
(String v:values){
43
                    
allowfiletype.add(v.trim());
44
                
}
45
            
}
46
            
// "Mime Type of gumby.gif is image/gif"
47
            
return

allowfiletype.contains(
new

MimetypesFileTypeMap().getContentType(uploadfile).toLowerCase())&&properties.keySet().contains(ext);
48
        
}
49
        
return

true
;
50
    
}
51
    
 
52
    
 
53
}
3、FileUpload主要上传和删除图片的功能

001
package
com.file.upload;
002
 
003
import
java.io.File;
004
import
java.util.Iterator;
005
import
java.util.List;
006
 
007
import
javax.servlet.http.HttpServletRequest;
008
 
009
import
org.apache.commons.fileupload.FileItem;
010
import
org.apache.commons.fileupload.FileUploadException;
011
import
org.apache.commons.fileupload.disk.DiskFileItemFactory;
012
import
org.apache.commons.fileupload.servlet.ServletFileUpload;
013
 
014
import
com.file.helper.FileConst;
015
import
com.file.helper.ReadUploadFileType;
016
 
017
public
class

FileUpload {
018
     
private

static
String uploadPath =

null
;
// 上传文件的目录
019
     
private

static
String tempPath =

null
;
// 临时文件目录
020
     
private

static
File uploadFile =

null
;
021
     
private

static
File tempPathFile =

null
;
022
     
private

static
int
sizeThreshold =
1024
;
023
     
private

static
int
sizeMax =
4194304
;
024
     
//初始化
025
     
static
{
026
           
sizeMax  = Integer.parseInt(FileConst.getValue(
"sizeMax"
));
027
           
sizeThreshold = Integer.parseInt(FileConst.getValue(
"sizeThreshold"
));
028
           
uploadPath = FileConst.getValue(
"uploadPath"
);
029
           
uploadFile =
new
File(uploadPath);
030
           
if

(!uploadFile.exists()) {
031
               
uploadFile.mkdirs();
032
           
}
033
           
tempPath = FileConst.getValue(
"tempPath"
);
034
           
tempPathFile =
new
File(tempPath);
035
           
if

(!tempPathFile.exists()) {
036
               
tempPathFile.mkdirs();
037
           
}
038
     
}
039
    
/**
040
     
* 上传文件
041
     
* @param request
042
     
* @return true 上传成功 false上传失败
043
     
*/
044
    
@SuppressWarnings
(
"unchecked"
)
045
    
public

static
boolean
upload(HttpServletRequest request){
046
        
boolean

flag =
true
;
047
        
//检查输入请求是否为multipart表单数据。
048
        
boolean

isMultipart = ServletFileUpload.isMultipartContent(request);
049
        
//若果是的话
050
        
if
(isMultipart){
051
            
/**为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。**/
052
            
try

{
053
                
DiskFileItemFactory factory =
new
DiskFileItemFactory();
054
                
factory.setSizeThreshold(sizeThreshold);
// 设置缓冲区大小,这里是4kb
055
                
factory.setRepository(tempPathFile);
// 设置缓冲区目录
056
                
ServletFileUpload upload =
new
ServletFileUpload(factory);
057
                
upload.setHeaderEncoding(
"UTF-8"
);
//解决文件乱码问题
058
                
upload.setSizeMax(sizeMax);
// 设置最大文件尺寸
059
                
List<FileItem>items = upload.parseRequest(request);
060
                
// 检查是否符合上传的类型
061
                
if
(!checkFileType(items))
return
false
;
062
                
Iterator<FileItem>itr = items.iterator();
//所有的表单项
063
                
//保存文件
064
                
while

(itr.hasNext()){
065
                     
FileItem item = (FileItem) itr.next();
//循环获得每个表单项
066
                     
if

(!item.isFormField()){
//如果是文件类型
067
                             
String name = item.getName();
//获得文件名 包括路径啊
068
                             
if
(name!=
null
){
069
                                 
File fullFile=
new

File(item.getName());
070
                                 
File savedFile=
new

File(uploadPath,fullFile.getName());
071
                                 
item.write(savedFile);
072
                             
}
073
                     
}
074
                
}
075
            
}
catch
(FileUploadException e) {
076
                
flag =
false
;
077
                
e.printStackTrace();
078
            
}
catch

(Exception e) {
079
                
flag =
false
;
080
                
e.printStackTrace();
081
            
}
082
        
}
else
{
083
            
flag =
false
;
084
            
System.out.println(
"the enctype must be multipart/form-data"
);
085
        
}
086
        
return

flag;
087
    
}
088
    
 
089
    
/**
090
     
* 删除一组文件
091
     
* @param filePath 文件路径数组
092
     
*/
093
    
public

static
void
deleteFile(String [] filePath){
094
        
if
(filePath!=
null

&& filePath.length>
0
){
095
            
for
(String path:filePath){
096
                
String realPath = uploadPath+path;
097
                
File delfile =
new
File(realPath);
098
                
if
(delfile.exists()){
099
                    
delfile.delete();
100
                
}
101
            
}
102
            
 
103
        
}
104
    
}
105
    
 
106
    
/**
107
     
* 删除单个文件
108
     
* @param filePath 单个文件路径
109
     
*/
110
    
public

static
void
deleteFile(String filePath){
111
        
if
(filePath!=
null

&& !
""
.equals(filePath)){
112
            
String [] path =
new
String []{filePath};
113
            
deleteFile(path);
114
        
}
115
    
}
116
    
 
117
    
/**
118
     
* 判断上传文件类型
119
     
* @param items
120
     
* @return
121
     
*/
122
    
private

static
Boolean checkFileType(List<FileItem>items){
123
        
Iterator<FileItem>itr = items.iterator();
//所有的表单项
124
        
while

(itr.hasNext()){
125
             
FileItem item = (FileItem) itr.next();
//循环获得每个表单项
126
             
if

(!item.isFormField()){
//如果是文件类型
127
                     
String name = item.getName();
//获得文件名 包括路径啊
128
                     
if
(name!=
null
){
129
                         
File fullFile=
new

File(item.getName());
130
                         
boolean

isType = ReadUploadFileType.readUploadFileType(fullFile);
131
                         
if
(!isType)
return
false
;
132
                         
break
;
133
                     
}
134
             
}
135
        
}
136
        
 
137
        
return

true
;
138
    
}
139
}
4、FileUploadServlet上传文件servlet 供外部调用

01
package
com.file.servlet;
02
 
03
import
java.io.IOException;
04
 
05
import
javax.servlet.ServletException;
06
import
javax.servlet.http.HttpServlet;
07
import
javax.servlet.http.HttpServletRequest;
08
import
javax.servlet.http.HttpServletResponse;
09
 
10
import
com.file.upload.FileUpload;
11
 
12
 
13
@SuppressWarnings
(
"serial"
)
14
public
class

FileUploadServlet
extends

HttpServlet {
15
    
 
16
    
public

void
doGet(HttpServletRequest request, HttpServletResponse response)
17
            
throws

ServletException, IOException {
18
        
this
.doPost(request, response);
19
    
}
20
 
21
    
 
22
    
public

void
doPost(HttpServletRequest request, HttpServletResponse response)
23
            
throws

ServletException, IOException {
24
        
FileUpload.upload(request);
25
    
}
26
 
27
}
5、DeleteFileServlet删除图片供外部调用

01
package
com.file.servlet;
02
 
03
import
java.io.IOException;
04
 
05
import
javax.servlet.ServletException;
06
import
javax.servlet.http.HttpServlet;
07
import
javax.servlet.http.HttpServletRequest;
08
import
javax.servlet.http.HttpServletResponse;
09
 
10
import
com.file.upload.FileUpload;
11
 
12
@SuppressWarnings
(
"serial"
)
13
public
class

DeleteFileServlet
extends

HttpServlet {
14
    
public

void
doGet(HttpServletRequest request, HttpServletResponse response)
15
            
throws

ServletException, IOException {
16
        
this
.doPost(request, response);
17
    
}
18
 
19
    
public

void
doPost(HttpServletRequest request, HttpServletResponse response)
20
            
throws

ServletException, IOException {
21
        
String [] file = request.getParameterValues(
"fileName"
);
22
        
FileUpload.deleteFile(file);
23
    
}
24
 
25
}
6、allow_upload_file_type.properties
gif=image/gif

jpg=mage/jpg,image/jpeg,image/pjpeg

png=image/png,image/x-pngimage/x-png,image/x-png

bmp=image/bmp

7、uploadConst.properties

sizeThreshold=4096

tempPath=c\:\\temp\\buffer\\

sizeMax=4194304

uploadPath=c\:\\upload\\

8外部调用

index.jsp

01
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
02
<%
03
String path = request.getContextPath();
04
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
05
%>
06
 
07
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
08
<
html
>
09
  
<
head
>
10
    
<
base

href="<%=basePath%>">
11
    
 
12
    
<
title
>My JSP 'index.jsp' starting page</
title
>
13
    
<
meta

http-equiv
=
"pragma"

content
=
"no-cache"
>
14
    
<
meta

http-equiv
=
"cache-control"

content
=
"no-cache"
>
15
    
<
meta

http-equiv
=
"expires"

content
=
"0"
>   
16
    
<
meta

http-equiv
=
"keywords"

content
=
"keyword1,keyword2,keyword3"
>
17
    
<
meta

http-equiv
=
"description"

content
=
"This is my page"
>
18
    
<!--
19
    
<link rel="stylesheet" type="text/css" href="styles.css">
20
    
-->
21
  
</
head
>
22
  
 
23
  
<
body
>
24
     
<
form

name
=
"myform"

action
=
"http://xxx.com/FileUploadServlet"

method
=
"post"

enctype
=
"multipart/form-data"
>
25
       
File:
26
       
<
input

type
=
"file"

name
=
"myfile"
><
br
>
27
       
<
br
>
28
       
<
input

type
=
"submit"

name
=
"submit"

value
=
"Commit"
>
29
    
</
form
>
30
  
</
body
>
31
</
html
>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: