`

使用 commons-fileupload-1.2.1.jar,commons-io-1.4.jar 配合实现上传

    博客分类:
  • Java
阅读更多

----------------------------------------------------------------------------------------------------------

转自: http://blog.csdn.net/xxxx1243/archive/2009/03/30/4037439.aspx

----------------------------------------------------------------------------------------------------------

 

commons-fileupload-1.2.1相对于commons-fileupload-1.1做了很多改进,废弃了一些函数。

该版本的上传代码如下:

 

public class UploadServlet extends HttpServlet {

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

        String path = request.getRealPath("/");
        
        //file upload factory
        DiskFileItemFactory factory = new  DiskFileItemFactory();
        //setting upload file path
        factory.setRepository(new File(path));                                                
        //set default memory size
        factory.setSizeThreshold(1024*1024);
        //
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        try {
            List<FileItem> list  = upload.parseRequest(request);
            
            for (FileItem item : list) {
                
                if(item.isFormField()){
                    String name = item.getFieldName();//input name
                    String value = item.getName();//input content
                    
                    request.setAttribute(name, value);
                }else{
                    String name = item.getFieldName();//input name
                    String value = item.getName();//input content
                    
                    value = value.substring(value.lastIndexOf("//")+1,value.length());
                    
                    
                    //1.--------------
                    //output file
                    OutputStream fileOutStream = new FileOutputStream(new File(path,value));
                    //input file
                    InputStream fileInputStream = item.getInputStream();
                    //file buffer
                    byte [] buffer = new byte[1024];
                    
                    //read
                    int length = 0;
                    while(( length = fileInputStream.read(buffer)) > 0){
                        fileOutStream.write(buffer,0,length);
                    }
                    
                    //close
                    fileInputStream.close();
                    fileOutStream.close();
                    
                    
                    //2.--------------
                    item.write(new File(path,value));
                    
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics