当前位置:编程学习 > JSP >>

jsp中利用servlet实现图片上传

 代码如下 复制代码

首先,页面中即JSP中需要如下的组件:

<h2 class="h2">
      上传照片:
     </h2>
     <form action="pic.do" method="post"
      enctype="multipart/form-data">
      <input type="file" name="file1" />
      <input type="submit" value=" 上传" />
     </form>

而后在servlet中可以通过如下代码来完成文件的上传操作:

if(path.equals("/pic")){

   //获得登录用户的id,用于创建新的文件夹,存放该用户上传的文件s
    HttpSession session = request.getSession();
    User user=(User)session.getAttribute("user");
    long id=user.getId();
   
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);
    try {
     List<FileItem> items = sfu.parseRequest(request);
     for(int i =0;i<items.size();i++){
      FileItem item =items.get(i);
      if(item.isFormField()){
       String name = item.getString();
       System.out.println("name"+name);
      }
      else{
       ServletContext context  = getServletContext();
       path  =context.getRealPath("upload");
       File file = new File(path+"\pic_"+id);
       file.mkdir();
      
       String fileName1 = item.getName();
       String fileName = fileName1.substring(fileName1.lastIndexOf("\")+1);
       file = new File(path+"\"+"pic_"+id+"\"+fileName);
      
       item.write(file);
      }
     }
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   
   }

补充:Jsp教程,Jsp/Servlet开发工具
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,