日期:2014-05-17  浏览次数:20667 次

java文件的上传和下载
//此处是下载
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
//得到下载文件的名字
String filename=request.getParameter("filename");
//解决中文乱码问题
  filename=new String(request.getParameter("filename").getBytes("iso-8859-1"),"gbk");
   
  //创建file对象
  File file=new File("E://gongzuo//apache-tomcat-6.0.30//temp//"+filename);
  //设置response的编码方式
  response.setContentType("application/x-msdownload");
   
  //写明要下载的文件的大小
  response.setContentLength((int)file.length());
  //设置附加文件名
  response.setHeader("Content-Disposition","attachment;filename="+filename);
   
  //解决中文乱码
  response.setHeader("Content-Disposition","attachment;filename="+new String
   
  (filename.getBytes("gbk"),"iso-8859-1"));  
   
  //读出文件到i/o流
  FileInputStream fis=new FileInputStream(file);
  BufferedInputStream buff=new BufferedInputStream(fis);
 
  byte [] b=new byte[1024];//相当于我们的缓存
 
  long k=0;//该值用于计算当前实际下载了多少字节
 
  //从response对象中得到输出流,准备下载
 
  OutputStream myout=response.getOutputStream();
 
  //开始循环下载
 
  while(k<file.length()){
  int j=buff.read(b,0,1024);
  k+=j;
  //将b中的数据写到客户端的内存
  myout.write(b,0,j);
  }
  //将写入到客户端的内存的数据,刷新到磁盘
  myout.flush();



   
   
   



out.flush();
out.close();
}





//上传 
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
response.setCharacterEncoding("utf-8");//响应消息内容能够正常显示中文
request.setCharacterEncoding("utf-8");//请求信息时
String filename="";//文件名称
String filepath="";//文件路径
String fileDosc="";//文件描述
long fileSize=0;//文件的大小
//创建文件上传的对象。借助 common-fileupload.jar
DiskFileItemFactory disk=new DiskFileItemFactory();//
long maxsize=1024*1024*5;//设置上传文件最大为5M
disk.setSizeThreshold(5102);//为上传文件在缓冲中设置一个大小为5K
String tmpFile=this.getServletContext().getRealPath("/");//获取上传路径
System.out.println(tmpFile);
File filo=new File(tmpFile+"tmpFile");//保存上传文件的目录
if(!filo.exists()){
filo.mkdirs();//服务器上是否有上传文件路径的目录如果没有则创建
}
disk.setRepository(filo);//将上传文件的目录加入到硬盘对象中

//创建能够解析上传文件的2进制类 由common-fileupload 与 io提供
ServletFileUpload sfu=new ServletFileUpload(disk);
sfu.setSizeMax(maxsize);//设置上传文件的最大容量
List list=null;
try{
list=sfu.parseRequest(request);//完成对上传文件的解析 同时将解析后的内容放到list里

}catch(Exception e){
out.println("<script language='javascript'>");
out.print(&quo