文件上传实例

 

1、Upload3.jsp代码

<body>

   <form action="${pageContext.request.contextPath}/servlet/UploadServlet3"method="post" enctype="multipart/form-data">

    上传用户:<input type="text" name="user"/><br/>

    上传文件:<input type="file" name="file1"/><br/>

    上传文件:<input type="file" name="file2"/><br/>

    <input type="submit" value="上传文件"/>

 

   </form>

  </body>

2.UploadServlet3.java代码

        private List fileType=Arrays.asList(".jpg",".jar",".txt");

    public void doPost(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

      

       //文件上传

       try {

           //(1)创建一个解析器工厂---FileItem对象

           DiskFileItemFactory factory=new DiskFileItemFactory();

           factory.setRepository(new File(this.getServletContext().getRealPath("/temp")));//将临时文件存在指定路径

           //(2)得到解析器

           ServletFileUpload upload=new ServletFileUpload(factory);

           upload.setHeaderEncoding("utf-8");

           upload.setFileSizeMax(1024*1024);

           upload.setProgressListener(new ProgerssHandle());//文件上传进度监听器

           //(3)对请求进行解析,有几个输入项,就会解析几个FileItem对象

           List<FileItem> list=upload.parseRequest(request);

           //(4)迭代list集合,对里边的每一个输入想进行处理(获取每一个输入项)

           for(FileItem item:list){

              //(5)判断输入的类型

              if(item.isFormField()){

                  //普通输入项

                  String inputName=item.getFieldName();

                  String inputValue=item.getString();

                  inputValue=new String(inputValue.getBytes("iso8859-1"),"utf-8");

                  System.out.println(inputName+"  "+inputValue);

                  //普通的输入有乱码如何解决

              }else{

                  //上传文件的输入项

                  String filename=item.getName();//上传文件的文件名字

                  if(!filename.trim().equals("")){//截取掉名字两边的空串,和空串比较看是否为空串决定是否执行程序

                 

                  filename=filename.substring(filename.lastIndexOf("\\")+1);//获取文件名(不包括路径)

                  String ext=filename.substring(filename.lastIndexOf("."));//获取扩展名

                  if(!fileType.contains(ext)){

                     request.setAttribute("message","上传失败--文件类型只能是jpg,txt,jar");

                     request.getRequestDispatcher("/message.jsp").forward(request, response);

                     return;

                  }

                  //得到输出留对象

                  InputStream is=item.getInputStream();

                  //首先确定上传文件要保存在那个目录下

                  String savePath=this.getServletContext().getRealPath("WEB-INF/upload");

                  //upload下建多级的子目录

                  savePath=generateFilePath(savePath,filename);

                   //对文件名进行了加工

                  filename=UUID.randomUUID().toString()+"_"+filename;

                  //构建输出流对象

                  FileOutputStream fos=new FileOutputStream(savePath+"\\"+filename);

                  byte[] buff=new byte[1024];

                  int len=0;

                  while((len=is.read(buff))>0){

                     fos.write(buff,0,len);

                  }

                  is.close();

                  fos.close();

                  item.delete();//删除的是临时文件

                  }

              }

           }

           request.setAttribute("message", "上传成功");

      

       }catch(FileUploadBase.FileUploadIOException e){

           request.setAttribute("message","上传文件太大不能超过1M");

       } catch (FileUploadException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

           request.setAttribute("message","上传失败");

       }

       request.getRequestDispatcher("/message.jsp").forward(request, response); 

       }

    public String generateFilePath(String path,String filename){

    // 产生目录结构的算法:hash目录

    int dir1=filename.hashCode() & 0x0f;//一级目录名

    int dir2=filename.hashCode() >>4 & 0x0f;

    String savePath=path+"\\"+dir1+"\\"+dir2;

    File f=new File(savePath);

    if(!f.exists()){//判断目录是否存在

       f.mkdirs();//多级目录结构创建

    }

   

    return savePath; 

}

   

class ProgerssHandle implements ProgressListener{

 

       public void update(long arg0, long arg1, int arg2) {

           // TODO Auto-generated method stub

           System.out.println("已经处理了"+arg0+"数据,总数据是"+arg1+"正在处理第"+arg2+"个数据");

 

       }

    }

你可能感兴趣的:(文件上传实例)