文件上传

注:文件上传需要借助第三方jar包!!!

commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar


package cn.fileUpload; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.util.UUID; 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.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UpServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置文件名中文乱码 request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter print = response.getWriter(); try { //得到上传文件的真实路径 String path = getServletContext().getRealPath("/WEB-INF/file"); //设置环境 DiskFileItemFactory factory = new DiskFileItemFactory();   //设置临时存放目录,该目录放在WEB-INF下面 factory.setRepository(new File(getServletContext().getRealPath("/WEB-INF/temp"))); //判断from是不是enctype=multipart/from-date,得到一个Boolean值 boolean isMun = ServletFileUpload.isMultipartContent(request); if(!isMun){ print.write("请将enctype设置为multipart/from-date"); return; } //得到servletFileLoad核心类 ServletFileUpload upload = new ServletFileUpload(factory); //通过这个类可以拿到文件的进度(具体显示到页面需要Ajax来实现):为一接口,通过匿名内部类实现里面的方法 upload.setProgressListener(new ProgressListener() { @Override public void update(long pBytesRead, long pContentLength, int pItems) { //pBytesRead:当前已读到的字节数,pContentLength:文件的长度,pItems:第几项 System.out.println("已读取:"+pBytesRead+",文件大小:"+pContentLength+",第几项:"+pItems); } }); //设置单个文件夹上传的大小 upload.setFileSizeMax(4*1024*1024); //设置总文件大小不的超过6M upload.setSizeMax(6*1024*1024); //解析(相当于拿到了所有的东东) List<FileItem> item = upload.parseRequest(request); //打印出内容 for(FileItem i : item){ //判断某项是否是普通的表单类型。 if(i.isFormField()){ //普通字段 String fileName = i.getFieldName(); //设置中文乱码,此处过滤器不管用 String fileValue = i.getString("utf-8"); System.out.println(fileName+"="+fileValue); }else{ //得到MIME类型 String m = i.getContentType(); //控制上传文件的类型 if(m.startsWith("image")){ //上传字段(得到一个输入流,后面通过该流去读目的地的内容) InputStream in = i.getInputStream(); //上传文件名(为jsp中文件一后面 的文件名) String name = i.getName(); //判断文件名是否为空(防止在上传多个文件时,上传的是看哪个值) if(name==null || "".equals(name.trim())){ continue; } name = name.substring(name.lastIndexOf("\\")+1); //产生一个唯一的id值 name = UUID.randomUUID()+"_"+name; //构建输出流,得到要写到那个文件的路径 String filePath = path+"\\"+name; //向filePath文件中写入数据 OutputStream out = new FileOutputStream(filePath); //这样就代表写到文件的末尾处 //OutputStream out = new FileOutputStream(filePath,true); byte[] b = new byte[1024]; int len = -1; while((len=in.read(b))!=-1){ out.write(b, 0, len); } out.close(); in.close(); //删除临时文件(必须在关闭流之后执行) i.delete(); }else{ print.write("请上传图片"); } } } } catch (org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e) { print.write("文件不能超过4M"); } catch (org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e) { print.write("总文件不能超过6M");  } catch (Exception e) { throw new RuntimeException(e); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

相关文章
相关标签/搜索