文件上传代码

  1 package cn.bd.Servlet;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 
  6 import java.io.PrintWriter;
  7 import java.util.Iterator;
  8 import java.util.List;
  9 
 10 import javax.servlet.ServletException;
 11 import javax.servlet.http.HttpServlet;
 12 import javax.servlet.http.HttpServletRequest;
 13 import javax.servlet.http.HttpServletResponse;
 14 
 15 import org.apache.commons.fileupload.FileItem;
 16 import org.apache.commons.fileupload.FileItemFactory;
 17 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 18 import org.apache.commons.fileupload.servlet.ServletFileUpload;
 19 
 20 import cn.bd.dao.impl.Product;
 21 import cn.bd.entity.EB_Product;
 22 
 23 public class ProductAdd extends HttpServlet {
 24 
 25     /**
 26      * Constructor of the object.
 27      */
 28     public ProductAdd() {
 29         super();
 30     }
 31 
 32     /**
 33      * Destruction of the servlet. <br>
 34      */
 35     public void destroy() {
 36         super.destroy(); // Just puts "destroy" string in log
 37         // Put your code here
 38     }
 39 
 40     /**
 41      * The doGet method of the servlet. <br>
 42      *
 43      * This method is called when a form has its tag value method equals to get.
 44      * 
 45      * @param request the request send by the client to the server
 46      * @param response the response send by the server to the client
 47      * @throws ServletException if an error occurred
 48      * @throws IOException if an error occurred
 49      */
 50     public void doGet(HttpServletRequest request, HttpServletResponse response)
 51             throws ServletException, IOException {
 52         request.setCharacterEncoding("utf-8");
 53         response.setContentType("text/html;charset:utf-8");
 54         response.setCharacterEncoding("utf-8");
 55         PrintWriter out = response.getWriter();
 56         
 57         String productName="";
 58         String productDetail="";
 59         String parentId="";
 60         String productPrice="";
 61         String productNumber="";
 62         
 63         request.setCharacterEncoding("utf-8");
 64         String uploadFileName=""; //上传的文件名
 65         String filedName=""; //表单字段元素的name属性
 66         boolean isMultipart=ServletFileUpload.isMultipartContent(request);
 67         
 68         //1.得到product文件夹上传到tomcat服务器后的绝对路径
 69         String uploadFilePath=request.getSession().getServletContext().getRealPath("images/product/");
 70         
 71         if(isMultipart){
 72             FileItemFactory factory=new DiskFileItemFactory();
 73             ServletFileUpload upload=new ServletFileUpload(factory);
 74             try {
 75                 List<FileItem> items=upload.parseRequest(request);
 76                 Iterator<FileItem> iter=items.iterator();
 77                 while(iter.hasNext()){
 78                     FileItem item=(FileItem)iter.next();
 79                     if(item.isFormField()){ //普通表单字段返回true,文件表单字段返回false
 80                         filedName=item.getFieldName();
 81                         if(filedName.equals("productName")){
 82                             productName =new String(item.getString().getBytes("iso-8859-1"),"utf-8"); //处理乱码
 83                         }
 84                         if(filedName.equals("productDetail")){
 85                             productDetail =new String(item.getString().getBytes("iso-8859-1"),"utf-8");
 86                         }
 87                         if(filedName.equals("parentId")){
 88                             parentId =new String(item.getString().getBytes("iso-8859-1"),"utf-8");
 89                         }
 90                         if(filedName.equals("productPrice")){
 91                             productPrice =new String(item.getString().getBytes("iso-8859-1"),"utf-8");
 92                         }
 93                         if(filedName.equals("productNumber")){
 94                             productNumber =new String(item.getString().getBytes("iso-8859-1"),"utf-8");
 95                         }
 96                     }else{
 97                         String fileName=item.getName();
 98                         if(fileName!=null&& !fileName.equals("")){
 99                             File fullFile=new File(item.getName());
100                             File saveFile=new File(uploadFilePath, fullFile.getName());
101                             item.write(saveFile);
102                             uploadFileName=fullFile.getName();
103                             /*System.out.println("上传成功后的文件名是:"+uploadFileName);*/
104                         }
105                     }
106                 }
107             } catch (Exception e) {
108                 e.printStackTrace();
109             }
110         }
111         /*/EasyBuy/manage/manage-result.jsp*/
112         
113         
114         
115         
116 /*        System.out.println("商品名称:"+productName);
117         System.out.println("商品描述:"+productDetail);
118         System.out.println("商品父类:"+parentId);
119         System.out.println("商品价格:"+productPrice);
120         System.out.println("商品数量:"+productNumber);
121         System.out.println("图片名称:"+uploadFileName);*/
122         
123         Product pro=new Product();
124         EB_Product p=new EB_Product();
125         
126         p.setEp_name(productName);
127         p.setEp_description(productDetail);
128         p.setEp_price(Float.valueOf(productPrice));
129         p.setEp_stock(Integer.valueOf(productNumber));
130         p.setEp_file_name(uploadFileName);
131         
132         int result=pro.addProduct(p);//加到数据库商品列表
133         
134         if(result>0){
135             request.getSession().removeAttribute("productList"); //删除会话中的商品列表,防止前台不更新
136             out.println("<script type='text/javascript'>alert('新增商品成功!');location.href='manage/product.jsp';</script>"); //后退
137             /*response.sendRedirect("manage/product.jsp");*/
138         }else{
139             out.println("<script type='text/javascript'>alert('新增商品异常!');history.back(-1);</script>"); //后退
140             return;
141         }
142         out.flush();
143         out.close();
144     }
145 
146     /**
147      * The doPost method of the servlet. <br>
148      *
149      * This method is called when a form has its tag value method equals to post.
150      * 
151      * @param request the request send by the client to the server
152      * @param response the response send by the server to the client
153      * @throws ServletException if an error occurred
154      * @throws IOException if an error occurred
155      */
156     public void doPost(HttpServletRequest request, HttpServletResponse response)
157             throws ServletException, IOException {
158 
159         doGet(request, response);
160     }
161 
162     /**
163      * Initialization of the servlet. <br>
164      *
165      * @throws ServletException if an error occurs
166      */
167     public void init() throws ServletException {
168         // Put your code here
169     }
170 
171 }
原文地址:https://www.cnblogs.com/taobd/p/6213115.html