`
leyoo
  • 浏览: 43827 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类

commons fileuplod 文件上传

阅读更多
文件上传2010-9-4 21:45
1.导入:commons-fileupload.jar  commons-io.jar

2.在服务器上的项目根目录下手动创建uploadFile文件夹用于存放上传文件,
  在uploadFile下创建temp文件夹用于缓存过大的图片。
  补充:也可通过代码实现上传时自动创建存放上传文件的目录。 

3.注意:上传图片路径:String uploadPath = req.getRealPath("/")+"/uploadFile";
        查看图片路径:String viewPath = request.getContextPath()+"/uploadFile";

4.不同操作系统获取文件路径分隔符
  包为java.util.Properties
  获取方法为Properties.getProperty(“file.separator”)
  补充:“/”在windows linux 系统上都适用。

5.上传用到的Servlet:FileUpload.java
public class FileUpload extends HttpServlet {
static Logger log = Logger.getLogger(FileUpload.class);
public void destroy() {
}
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
   res.setContentType( "text/html; charset=GBK");
   String picture_name = "";
   String picture_id = "";
   String product_id = "";
   PrintWriter out=res.getWriter();
   String uploadPath = req.getRealPath("/")+"/uploadFile"; // 用于存放上传文件的目录
   DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(1024*1024*4);
        // the location for saving data that is larger than getSizeThreshold()
        factory.setRepository(new File(uploadPath+"/temp")); // 用于存放临时文件的目录
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum size before a FileUploadException will be thrown
        upload.setSizeMax(1024*1024*8);
        try{
        List fileItems = upload.parseRequest(req);
        // assume we know there are two files. The first file is a small
        // text file, the second is unknown and is written to a file on
        // the server
        Iterator iter = fileItems.iterator();
//  正则匹配,过滤路径取文件名
     String regExp=".+\\\\(.+)$";
//  过滤掉的文件类型
  String[] errorType={".exe",".com",".cgi",".asp"};
     Pattern p = Pattern.compile(regExp);
     // 保存文件域的信息数组
        while (iter.hasNext()) {
         FileItem item = (FileItem)iter.next();
         //是文件域的所有表单信息
         if(item.isFormField()){
        picture_name = item.getString();
        String[] params = picture_name.split("==");
        if(params!=null&&params.length>1){
        product_id = params[0];
        picture_id = params[1];
        }
        log.error("==========产品ID="+product_id+"====图片ID="+picture_id);
         }
         //不是文件域的所有表单信息
         if (!item.isFormField()) {
             String name = item.getName();
             long size = item.getSize();
             if((name==null||name.equals("")) && size==0)
                 continue;
          Matcher m = p.matcher(name);
         boolean result = m.find();
         if (result){
             for (int temp=0;temp<errorType.length;temp++){
             if (m.group(1).endsWith(errorType[temp])){
                   throw new IOException(name+": wrong type");
             }
             }
             try{
//         保存上传的文件到指定的目录
//         在下文中上传文件至数据库时,将对这里改写
//                      item.write(new File(uploadPath +"\\"+ m.group(1)));
     //取到上传文件的扩展名
                 String extand = m.group(1).substring(m.group(1).indexOf("."));
//                  上传新图片
                 String picName = RandomNum.getRandomNum()+extand;
                                     //将图片重新命名为任意位数的随机数
                 String picPath = uploadPath +"/"+ picName; //新图片路径
                 item.write(new File(picPath));//写入新图片
                 log.error("图片上传成功!");
                 out.print("图片文件上传成功!<br>"+name+"&nbsp;&nbsp;"+size+"<br>");
                     PictureManager pictureManager = PictureManager.getInstance();
//                      Picture picture = pictureManager.searchPicture(picture_id);
//                      log.error("=======旧图片名称====="+picture.getPicture_path());
                    
                     //构建新图片数据库信息保存对象
                     Picture pic = new Picture();
                     pic.setProduct_id(product_id);
                     pic.setPicture_id(picture_id);
                     log.error("=======product_id====="+product_id);
                     pic.setPicture_path(picName);
                     if("0".equals(picture_id)){
                    //添加记录
                    pictureManager.addPicture(pic);
                    log.error("添加记录成功!");
                    res.sendRedirect("../servlet/PictureServlet?action=list&product_id="+product_id);
                     }else{
                    //删除旧图片
                    Picture picture = pictureManager.searchPicture(picture_id);
                    String oldpicPath = uploadPath +"/"+picture.getPicture_path();  //获取旧图片路径
                    oldpicPath=oldpicPath.replaceAll("\\\\", "/");
                    File oldPic = new File(oldpicPath);
                    //oldPic.createNewFile();
                    if(oldPic.exists()){
                    oldPic.delete();
                    log.error("旧图片删除成功!");
                    }
                    //更新记录
                    pictureManager.modifyPicture(pic);
                    log.error("更新记录成功!picName="+picName);
                    res.sendRedirect("../servlet/PictureServlet?action=list&product_id="+product_id);
                     }
                   
                   
                   }
                   catch(Exception e){
                     out.println(e);
                     log.error("图片上传失败!");
                   }
                }
               else
               {
                 throw new IOException("fail to upload");
               }
               }
           }
        }
         catch (IOException e){
           out.println(e);
         }
         catch (FileUploadException e){
              out.println(e);
         }
//  保存上传的文件到指定的目录
//  在下文中上传文件至数据库时,将对这里改写
    }

/**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occure
  */
public void init() throws ServletException {
  // Put your code here
}
}
6. 在web.xml文件中配置上传的servlet
  <servlet>
    <servlet-name>FileUpload</servlet-name>
    <servlet-class>com.servlet.FileUpload</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>FileUpload</servlet-name>
    <url-pattern>/servlet/FileUpload</url-pattern>
  </servlet-mapping>
  <servlet-mapping>

7.如果可以最好将servlet放在项目的根目录下。
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics