CommonUpload上传图片~~~

优点:app

一、能够实现一个或多个文件的上传,也能够接收普通的form表单数据。
二、简单测试了一下,对内存的占用仍是能够忍受的,并且速度也能够。偶尔会致使内存使用的上升并且不会降低,长时间后是否会降下来尚未测试。

关键点:
一、提交文件上传的form的method属性为post,enctype属性为multipart/form-data。
二、input标签须要有name属性,不然取不到内容。ide

页面代码实现(部分):post

  <form action="goods?id=addSecondPicture" method="post" enctype="multipart/form-data">
  <tr>
   <td height="60" class="title" rowspan="2">上传图片<br/>(限制二张)</td>
   <td colspan="4"><input type="file" name="file1"><font color="red">(选填)</font></td>
   <td></td>
  </tr>
  <tr>
    <td colspan="4"><input type="file" name="file2"><font color="red">(选填)</font></td>
   <td><input type="submit" value="上传"></td>
  </tr>
  </form>测试


servlet映射:
 this

  <servlet>
    <description></description>
    <display-name>GoodServlet</display-name>
    <servlet-name>GoodServlet</servlet-name>
    <servlet-class>city.matcha.admin.servlet.GoodServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GoodServlet</servlet-name>
    <url-pattern>/admin/goods</url-pattern>
  </servlet-mapping>url

servlet代码(关键部分):spa

List<Picture> pList = new ArrayList<Picture>();
  DiskFileItemFactory factory = new DiskFileItemFactory();
     factory.setSizeThreshold(1024);
  String SQLPath = "";
  String rootPath = "";
  String uploadPath = "";
  try {
   ServletFileUpload fu = new ServletFileUpload(factory);
   fu.setSizeMax(2*1024*1024);
   List fileitems = fu.parseRequest(request);
   if(fileitems!=null){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD-HH-mm-ss");
    rootPath = this.getServletContext().getRealPath("\\");
    for(int i=0;i<fileitems.size();i++){
     FileItem item = (FileItem)fileitems.get(i);
     if(item.isFormField()){
      continue;
     }else{
       String filePath = item.getName();
       if(filePath!=null&&!filePath.trim().equals("")){
        int point = filePath.lastIndexOf("\\");
        String fileName = filePath.substring(point+1,filePath.length());
        uploadPath = rootPath+"p_w_picpaths\\"+sdf.format(new Date())+fileName;
        SQLPath = "..\\p_w_picpaths\\"+sdf.format(new Date())+fileName;
        item.write(new File(uploadPath));
        Picture pic = new Picture();
        pic.setPurl(SQLPath);
        pList.add(pic);
       }
     }
    }
    
   }
        } catch (Exception ex) {
         ex.printStackTrace();
        }orm

若是有什么不懂的地方,能够留言,我会尽力回答~~~感谢光临~~~图片

相关文章
相关标签/搜索