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;
importjavax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
importorg.apache.commons.fileupload.FileItem;
importorg.apache.commons.fileupload.disk.DiskFileItemFactory;
importorg.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 extendsHttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponseresponse)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponseresponse)
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(); //创建磁盘工厂
factory.setRepository(tmp); //文件缓存路径
factory.setSizeThreshold(10 * 1096 );
ServletFileUpload sfu = new ServletFileUpload(factory); //创建处理工具
sfu.setSizeMax(10*1024*1024); //服务器端可以接收的最大文件大小,-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"); //设置图片相对路径
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】
下载似乎就更简单了, packagecom.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;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class FileDownloadServlet extendsHttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponseresponse)
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); //将文件转码 UTF-8
inStream = new FileInputStream(filename);
response.reset(); //必须reset,否则会出现文件不完整
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment;filename=\"" + attchname +"\"");
//循环取出流中的数据
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转码
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, HttpServletResponseresponse)
throws ServletException {
this.doPost(request, response);
}
}