Java文件上傳組件 common-fileUpload 使用教程
最近項目中,在發布商品的時候要用到商品圖片上傳功能(網站前臺和后臺都要用到),所以單獨抽出一個項目來供其他的項目進行調用 ,對外透露的接口的為兩個servlet供外部上傳和刪除圖片,利用到連個jarcommons-fileupload-1.2.1.jar,commons-io-1.4.jar
項目結構如下:

其中com.file.helper主要提供讀相關配置文件的幫助類
com.file.servlet 是對外提供調用上傳和刪除的圖片的servlet
com.file.upload 是主要提供用于上傳和刪除圖片的接口
1、FileConst類主要是用讀取文件存儲路徑和設置文件緩存目錄 允許上傳圖片的最大值
package com.file.helper;
import java.io.IOException;
import java.util.Properties;
public class FileConst {
private static Properties properties= new Properties();
static{
try {
properties.load(ReadUploadFileType.class.getClassLoader().getResourceAsStream("uploadConst.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getValue(String key){
String value = (String)properties.get(key);
return value.trim();
}
}2、ReadUploadFileType讀取允許上傳圖片的類型和判斷上傳的文件是否符合約束的文件類型
package com.file.helper;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.activation.MimetypesFileTypeMap;
/**
* 讀取配置文件
* @author Owner
*
*/
public class ReadUploadFileType {
private static Properties properties= new Properties();
static{
try {
properties.load(ReadUploadFileType.class.getClassLoader().getResourceAsStream("allow_upload_file_type.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 判斷該文件是否為上傳的文件類型
* @param uploadfile
* @return
*/
public static Boolean readUploadFileType(File uploadfile){
if(uploadfile!=null&&uploadfile.length()>0){
String ext = uploadfile.getName().substring(uploadfile.getName().lastIndexOf(".")+1).toLowerCase();
List<String> allowfiletype = new ArrayList<String>();
for(Object key : properties.keySet()){
String value = (String)properties.get(key);
String[] values = value.split(",");
for(String v:values){
allowfiletype.add(v.trim());
}
}
// "Mime Type of gumby.gif is image/gif"
return allowfiletype.contains( new MimetypesFileTypeMap().getContentType(uploadfile).toLowerCase())&&properties.keySet().contains(ext);
}
return true;
}
}3、FileUpload主要上傳和刪除圖片的功能
package com.file.upload;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
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 com.file.helper.FileConst;
import com.file.helper.ReadUploadFileType;
public class FileUpload {
private static String uploadPath = null;// 上傳文件的目錄
private static String tempPath = null; // 臨時文件目錄
private static File uploadFile = null;
private static File tempPathFile = null;
private static int sizeThreshold = 1024;
private static int sizeMax = 4194304;
//初始化
static{
sizeMax = Integer.parseInt(FileConst.getValue("sizeMax"));
sizeThreshold = Integer.parseInt(FileConst.getValue("sizeThreshold"));
uploadPath = FileConst.getValue("uploadPath");
uploadFile = new File(uploadPath);
if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
tempPath = FileConst.getValue("tempPath");
tempPathFile = new File(tempPath);
if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
/**
* 上傳文件
* @param request
* @return true 上傳成功 false上傳失敗
*/
@SuppressWarnings("unchecked")
public static boolean upload(HttpServletRequest request){
boolean flag = true;
//檢查輸入請求是否為multipart表單數據。
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//若果是的話
if(isMultipart){
/**為該請求創建一個DiskFileItemFactory對象,通過它來解析請求。執行解析后,所有的表單項目都保存在一個List中。**/
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(sizeThreshold); // 設置緩沖區大小,這里是4kb
factory.setRepository(tempPathFile);// 設置緩沖區目錄
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");//解決文件亂碼問題
upload.setSizeMax(sizeMax);// 設置最大文件尺寸
List<FileItem> items = upload.parseRequest(request);
// 檢查是否符合上傳的類型
if(!checkFileType(items)) return false;
Iterator<FileItem> itr = items.iterator();//所有的表單項
//保存文件
while (itr.hasNext()){
FileItem item = (FileItem) itr.next();//循環獲得每個表單項
if (!item.isFormField()){//如果是文件類型
String name = item.getName();//獲得文件名 包括路徑啊
if(name!=null){
File fullFile=new File(item.getName());
File savedFile=new File(uploadPath,fullFile.getName());
item.write(savedFile);
}
}
}
} catch (FileUploadException e) {
flag = false;
e.printStackTrace();
}catch (Exception e) {
flag = false;
e.printStackTrace();
}
}else{
flag = false;
System.out.println("the enctype must be multipart/form-data");
}
return flag;
}
/**
* 刪除一組文件
* @param filePath 文件路徑數組
*/
public static void deleteFile(String [] filePath){
if(filePath!=null && filePath.length>0){
for(String path:filePath){
String realPath = uploadPath+path;
File delfile = new File(realPath);
if(delfile.exists()){
delfile.delete();
}
}
}
}
/**
* 刪除單個文件
* @param filePath 單個文件路徑
*/
public static void deleteFile(String filePath){
if(filePath!=null && !"".equals(filePath)){
String [] path = new String []{filePath};
deleteFile(path);
}
}
/**
* 判斷上傳文件類型
* @param items
* @return
*/
private static Boolean checkFileType(List<FileItem> items){
Iterator<FileItem> itr = items.iterator();//所有的表單項
while (itr.hasNext()){
FileItem item = (FileItem) itr.next();//循環獲得每個表單項
if (!item.isFormField()){//如果是文件類型
String name = item.getName();//獲得文件名 包括路徑啊
if(name!=null){
File fullFile=new File(item.getName());
boolean isType = ReadUploadFileType.readUploadFileType(fullFile);
if(!isType) return false;
break;
}
}
}
return true;
}
}4、FileUploadServlet上傳文件servlet 供外部調用
package com.file.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.file.upload.FileUpload;
@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileUpload.upload(request);
}
}5、DeleteFileServlet刪除圖片供外部調用
package com.file.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.file.upload.FileUpload;
@SuppressWarnings("serial")
public class DeleteFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String [] file = request.getParameterValues("fileName");
FileUpload.deleteFile(file);
}
}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
<%@ 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 '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">
-->
</head>
<body>
<form name="myform" action="http://xxx.com/FileUploadServlet" method="post" enctype="multipart/form-data">
File:
<input type="file" name="myfile"><br>
<br>
<input type="submit" name="submit" value="Commit">
</form>
</body>
</html>轉自:http://blog.csdn.net/ajun_studio/article/details/6639306
本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!