commons-upload.jar 實現(xiàn)文件的上傳下載
Posted on 2009-06-13 22:31 Gavin.lee 閱讀(2759) 評論(0) 編輯 收藏 所屬分類: web 積累(前端 + 后臺)今天幫個朋友部署了他的博客(JSP + JAVA + SQLSERVER 2000),設(shè)計到頭像上傳,部署完了,bean有下小叉叉,郁悶,當(dāng)時就糗了。恨不得找個地縫鉆進(jìn)去。晚上回來找找資料,總結(jié)了一把,也算是有點收獲了。這個我以前用過,呵,都忘了具體怎么實現(xiàn)的了。就象網(wǎng)上雜七雜八說的一樣,很多種實現(xiàn)方法,多利用各種插件,我這里就是用apache的commons-fileupload。先去下這個包。然后接著下面。現(xiàn)在知道了,很簡單。
http://www.cnblogs.com/yyw84/archive/2007/06/27/797652.html,這里有個非常好的框架。
【upload】
package com.handson.bbs.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.handson.bbs.bo.UserBO;
import com.handson.bbs.model.User;
/**
* **********************************************
* @description 文件上傳
* 針對本項目,上傳圖片在uploadFile/Image
* 緩存目錄 c:\\tmp\\ 目錄下
* 照片上傳后,后面代碼處理及時更新用戶照片。
* @author Gavin.lee
* @date 2009-6-13 21:35:47
* @version 1.0
***********************************************
*/
public class UploadPhotoServlet 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 filepath = this.getServletContext().getRealPath("/uploadFile/Image/"); //容器相對路徑
File tmp = new File("c:\\tmp\\");
if(! tmp.exists()) {
tmp.mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory(); //創(chuàng)建磁盤工廠
factory.setRepository(tmp); //文件緩存路徑
factory.setSizeThreshold(10 * 1096 );
ServletFileUpload sfu = new ServletFileUpload(factory); //創(chuàng)建處理工具
sfu.setSizeMax(10*1024*1024); //服務(wù)器端可以接收的最大文件大小,-1表示無上限
String filename = null;
try {
List<FileItem> list = sfu.parseRequest(request); //解析
FileItem item= list.get(0);
filename = item.getName();
if(filename.equals("")) {
request.getRequestDispatcher("/com/visualizePhoto.jsp").forward(request, response);
return ;
}
int pos = filename.lastIndexOf("."); //取圖片文件格式
if(pos > 0) {
Date date = new Date();
filename =filepath+'/'+ date.getTime()+filename.substring(pos);
}
item.write(new File(filename)); //寫到磁盤
} catch(Exception e) {
e.printStackTrace();
}
// 只針對文件上傳的話,后面代碼不用看了,后面是針對及時更新用戶信息(照片)
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
int pos = filename.indexOf("uploadFile"); //設(shè)置圖片相對路徑
if(pos > 0) {
filename = filename.substring(pos,pos+10)+'/'+filename.substring(pos+11);
}
user.setPhoto(filename);
UserBO userBo = UserBO.getInstance();
if(userBo.updateUser(user)){
session.setAttribute("user", user);
request.getRequestDispatcher("/com/visualizePhoto.jsp").forward(request, response);
}
}

}
【download】
下載似乎就更簡單了,
package com.Gavin.tools.fileupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileDownloadServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
String filename = request.getParameter("file_name");
if (filename == null)
filename = "";
filename = filename.trim();

InputStream inStream = null;
String attchname = "";

byte[] b = new byte[100];
int len = 0;
try {
attchname = getAttachName(filename); //取得附件的名稱
filename = getRealName(request, filename); //取得附件的全路徑
if (filename == null) {
System.out.println("文件不存在,或者禁止下載");
return;
}
attchname = toUtf8String(attchname); //將文件轉(zhuǎn)碼 UTF-8
inStream = new FileInputStream(filename);
response.reset(); //必須reset,否則會出現(xiàn)文件不完整
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment; filename=\"" + attchname + "\"");
//循環(huán)取出流中的數(shù)據(jù)
while ((len = inStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
inStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

//取得附件的名稱
public static String getAttachName(String filename) {
if (filename == null)
return "";
filename = filename.trim();
int pos = 0;
pos = filename.lastIndexOf("\\");
if (pos > -1) {
filename = filename.substring(pos + 1);
}
pos = filename.lastIndexOf("/");
if (pos > -1) {
filename = filename.substring(pos + 1);
}
pos = filename.lastIndexOf(File.separator);
if (pos > -1) {
filename = filename.substring(pos + 1);
}
return filename;
}

//UTF8轉(zhuǎn)碼
public static String toUtf8String(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
String s_utf8 = sb.toString();
sb.delete(0, sb.length());
sb.setLength(0);
sb = null;
return s_utf8;
}

//取得下載文件的真實全路徑名稱
private String getRealName(HttpServletRequest request, String filename) {
if (request == null || filename == null)
return null;
filename = filename.trim();
if (filename.equals(""))
return null;

String filepath = request.getRealPath(filename);
if (filepath == null)
return null;
File file = new File(filepath);
if (!file.exists())
return null;
return filepath;
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
this.doPost(request, response);
}

}
同樣這個要進(jìn)行web.xml配置一下servlet。完工 O(∩_∩)O~, 這里也有一個不錯的 http://www.cnblogs.com/ungshow/archive/2009/01/12/1374491.html
http://www.cnblogs.com/yyw84/archive/2007/06/27/797652.html,這里有個非常好的框架。
【upload】




















































































【download】
下載似乎就更簡單了,






































































































































