Posted on 2009-06-13 22:31
Gavin.lee 阅读(2750)
评论(0) 编辑 收藏 所属分类:
web 积累(前端 + 后台)
今天帮个朋友部署了他的博客(JSP + JAVA + SQLSERVER 2000),设计到头像上传,部署完了,bean有下小叉叉,郁闷,当时就糗了。恨不得找个地缝钻进去。晚上回来找找资料,总结了一把,也算是有点收获了。这个我以前用过,呵,都忘了具体怎么实现的了。就象网上杂七杂八说的一样,很多种实现方法,多利用各种插件,我这里就是用apache的commons-fileupload。先去下这个包。然后接着下面。现在知道了,很简单。
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(); //创建磁盘工厂
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】
下载似乎就更简单了,
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); //将文件转码 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, HttpServletResponse response)

throws ServletException
{
this.doPost(request, response);
}

}

同样这个要进行web.xml配置一下servlet。完工 O(∩_∩)O~, 这里也有一个不错的
http://www.cnblogs.com/ungshow/archive/2009/01/12/1374491.html