Servlet上传下载

来源:互联网 发布:海贼王漫画885知乎 编辑:程序博客网 时间:2024/05/22 12:59

上传:

package com.yl.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {
 /**
  * 上传文件的目录
  *
  */
 private String uploadPath = null;;

 /**
  * 临时文件目录
  *
  */
 private String tempPath = null;
 File tempPathFile;

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  try {
   
   
   DiskFileItemFactory factory = new DiskFileItemFactory();
   // 设置缓冲区大小,这里是4kb
   factory.setSizeThreshold(4096);
   // 设置缓冲区目录
   factory.setRepository(tempPathFile);
   ServletFileUpload upload = new ServletFileUpload(factory);
   // 设置最大文件尺寸,这里是100MB
   upload.setSizeMax(119430400);
   // 得到所有的文件
   List<FileItem> items = upload.parseRequest(request);
   Iterator<FileItem> i = items.iterator();
   // 通过循环,我们可以将客户端上传的多个文件都放到指定目录下去
   while (i.hasNext()) {
    FileItem fi = (FileItem) i.next();
    String fileName = fi.getName();
    if (fileName != null) {
     File fullFile = new File(fi.getName());
     // 这里为了上传中文文件,需要对文件名进行转码,否则上传的中文文件名会出现乱码
     File savedFile = new File(uploadPath, new String(fullFile.getName().getBytes(),"gbk"));
     fi.write(savedFile);
    }
   }
   System.out.print("upload succeed");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * 在servlet的初始化方法中创建上传目录
  *
  *
  * @throws ServletException
  */
 @Override
 public void init() throws ServletException {
  //this.uploadPath="D://UpLoadFile//file";
  this.uploadPath=this.getServletContext().getRealPath("/")+"file";
  this.tempPath=this.uploadPath+"/temp";
  File uploadFile = new File(uploadPath);
  if (!uploadFile.exists()) {
   uploadFile.mkdirs();
  }
  File tempPathFile = new File(tempPath);
  if (!tempPathFile.exists()) {
   tempPathFile.mkdirs();
  }
 }
}
下载:

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package com.yl.struts.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * MyEclipse Struts
 * Creation date: 05-08-2010
 *
 * XDoclet definition:
 * @struts.action validate="true"
 */
public class DownfileAction extends Action {
 /*
  * Generated Methods
  */

 /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  */
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  String filename=request.getParameter("filename");
  //String realRoot="D://UpLoadFile//file//";
  String realRoot=this.getServlet().getServletContext().getRealPath("/")+"file"+"//";
  //System.out.println("Down File .........."+realRoot);
  String realPath=null;
  try {
   //String realPath=realRoot+"//userFile//"+new String(filename.getBytes("ISO-8859-1"),"gbk");
   String str=new String(filename.getBytes("ISO-8859-1"),"gbk");
    realPath=realRoot+str;
  // System.out.println("realPath="+realPath);
   File file=new File(realPath);
   //response.setContentType("application/x-msdownload;charset=gbk");
   response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(new String(filename.getBytes("ISO-8859-1"),"gbk")));
   System.out.println();
   final String contentType="application/x-msdownload;charset=gbk";
   
  } catch (UnsupportedEncodingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  OutputStream output=null;
  FileInputStream fileinput=null;
  try {
   output=response.getOutputStream();
   fileinput=new FileInputStream(realPath);
   byte[] b=new byte[1024];//缓冲区
   int i=0;
   while((i=fileinput.read(b))>0)
   {
    output.write(b,0, i);
   }
   output.flush();
  } catch (Exception e) {
   // TODO: handle exception
   System.out.println("Down File Fail");
  }
  finally{
   if(fileinput!=null){
    try {
     fileinput.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    fileinput=null;
   }
   if(output!=null){
    try {
     output.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    output=null;
   }
  }
  return mapping.findForward("downfile");
 }
}

原创粉丝点击