package cn.com.qmhd.tools; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.com.qmhd.tools.Log; import com.oreilly.servlet.multipart.FilePart; import com.oreilly.servlet.multipart.MultipartParser; import com.oreilly.servlet.multipart.ParamPart; import com.oreilly.servlet.multipart.Part; public class UpDownUtils{ public boolean download(HttpServletRequest request, HttpServletResponse response, String filePath, String strFileName, String strType) { try { File f = new File(filePath); response.reset(); response.setContentType( strType );//设置下载文件的类型 response.setHeader("content-disposition","attachment; filename="+strFileName); //设置下载的文件名 long fileLength=f.length(); String length1=String.valueOf(fileLength); response.setHeader("Content_Length",length1); //下载文件的大小 InputStream in = new FileInputStream( f ); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[2097152]; int ins = in.read(buffer);//读取字节到buffer中 //ins == -1 时 。就已经是文件的结尾了 while ( ins != -1 ) { out.write(buffer, 0, ins);//将缓存buffer中的数据写到文件中 ins = in.read(buffer); } in.close(); out.flush(); out.close(); return true; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } public String upload(HttpServletRequest request, String strFileName , int fileSize) { try { MultipartParser mp = new MultipartParser(request,fileSize * 1024 * 1024); //所有表单域都是Part实例 Part part; //遍历请求中的所有表单域 while((part = mp.readNextPart()) != null ){ //取得表单域的name属性值 String name = part.getName(); //对于普通表单域 if(part.isParam()){ //取得普通表单域的值 ParamPart paramPart = (ParamPart) part; String value = paramPart.getStringValue("GBK"); //System.out.println("Some common form fields:<br>name=" + name + ";value=" + value + "<br>"); } //对于文件域 else if(part.isFile()){ //获取文件上传域 FilePart filePart = (FilePart) part; //System.out.println( filePart.getFileName() ); //fileName = filePart.getFileName(); if(strFileName != null){ //输出文件内容 long size = filePart.writeTo(new File(request.getRealPath("/")+"upload/"+strFileName)); //System.out.println("Upfile:<br>File name field=" + name + ";fileName=" + strFileName + "<br>"); }else{ //文件名为空 return "error"; } System.out.flush(); } } return strFileName; } catch (Exception e) { Log.getInstance().printError(this.getClass().getName(), e.toString()); e.printStackTrace(); return "error"; } } }