代码改变世界

文件上传

2018-06-27 11:01  程序员bu睡懒觉  阅读(170)  评论(0编辑  收藏  举报
1

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>

<body>
<form action="uploadFiles" method="post" enctype="multipart/form-data">
${message}
<table>
<tr>
<td>商品名称:</td>
<td><input name="name"></td>
</tr>
<tr>
<td>商品数量:</td>
<td><input name="num"></td>
</tr>
<tr>
<td>商品价格:</td>
<td><input name="price"></td>
</tr>
<tr>
<td>商品主图片:</td>
<td><input type="file" name="upMainFile" ></td>
</tr>
<tr>
<td>商品其他图片:</td>
<td><input type="file" name="upFile1"></td>
</tr>
<tr>
<td>商品其他图片:</td>
<td><input type="file" name="upFile2"></td>
</tr>
<tr>
<td>商品其他图片:</td>
<td><input type="file" name="upFile3"></td>
</tr>
<tr>
<td>商品其他图片:</td>
<td><input type="file" name="upFile4"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="上传"></td>
</tr>
</table>
</form>
<a href="dispalyServlet">显示信息</a>
</body>
</html>

package com.oracle.util;

public class FileUtil {

    
    
    
    
    //获取原文件名
    public static String getFileName(String strFile){
        return strFile.substring(strFile.lastIndexOf("=")+2,strFile.length()-1);
    }
    //获取文件类型
    public static String getFileType(String fileName){
        return fileName.substring(fileName.lastIndexOf("."), fileName.length());
    }
}

 

  1 package com.oracle.servlet;
  2 
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 import java.sql.Connection;
  6 import java.sql.SQLException;
  7 import java.util.ArrayList;
  8 import java.util.List;
  9 import java.util.UUID;
 10 
 11 import javax.servlet.ServletException;
 12 import javax.servlet.annotation.MultipartConfig;
 13 import javax.servlet.annotation.WebServlet;
 14 import javax.servlet.http.HttpServlet;
 15 import javax.servlet.http.HttpServletRequest;
 16 import javax.servlet.http.HttpServletResponse;
 17 import javax.servlet.http.Part;
 18 
 19 import com.oracle.bean.Img;
 20 import com.oracle.bean.Produce;
 21 import com.oracle.dao.DbUtil;
 22 import com.oracle.service.ImgService;
 23 import com.oracle.service.ProduceService;
 24 import com.oracle.util.FileUtil;
 25 
 26 @WebServlet("/uploadFiles")
 27 @MultipartConfig
 28 public class uploadFiles extends HttpServlet {
 29 
 30     public void doGet(HttpServletRequest request, HttpServletResponse response)
 31             throws ServletException, IOException {
 32 
 33         doPost(request, response);
 34     }
 35 
 36     public void doPost(HttpServletRequest request, HttpServletResponse response)
 37             throws ServletException, IOException {
 38         final String HEADER_INFO = "Content-Disposition";
 39         final String PATH = "imgs/";
 40         // 设置字符集
 41         request.setCharacterEncoding("utf-8");
 42         // 获取商品信息
 43         String name = request.getParameter("name");
 44         String strNum = request.getParameter("num");
 45         Integer num = null;
 46         if (!"".equals(strNum)) {
 47             num = Integer.parseInt(strNum);
 48         }
 49         String strPrice = request.getParameter("price");
 50         Double price = null;
 51         if (!"".equals(strPrice)) {
 52             price = Double.parseDouble(strPrice);
 53         }
 54         // Integer id, String name, Integer num, Double price
 55         Produce pro = new Produce(null, name, num, price);
 56         // 获取文件流
 57         Part part0 = request.getPart("upMainFile");
 58         Part part1 = request.getPart("upFile1");
 59         Part part2 = request.getPart("upFile2");
 60         Part part3 = request.getPart("upFile3");
 61         Part part4 = request.getPart("upFile4");
 62         List<Part> listP = new ArrayList<Part>();
 63         listP.add(part0);
 64         listP.add(part1);
 65         listP.add(part2);
 66         listP.add(part3);
 67         listP.add(part4);
 68         // 将文件存入实体集合
 69         List<Img> list = new ArrayList<Img>();
 70         Img img = null;
 71         for (Part p : listP) {
 72             if (p.getSize() != 0) {
 73                 // 获取文件名
 74                 String strFile = p.getHeader(HEADER_INFO);
 75                 String fileName = FileUtil.getFileName(strFile);
 76                 // 获取文件后缀
 77                 String fileType = FileUtil.getFileType(fileName);
 78                 // 获取新文件名
 79                 String newFileName = UUID.randomUUID().toString()
 80                         .replaceAll("-", "");
 81                 // 获取服务器文件存储路径
 82                 String path = this.getServletConfig().getServletContext()
 83                         .getRealPath("/")
 84                         + PATH;
 85                 String newFile = newFileName + fileType;
 86                 // Integer id, String fileName, String uuidName, Integer
 87                 // produceId
 88                 img = new Img(null, fileName, newFile, null);
 89                 p.write(path + newFile);
 90                 list.add(img);
 91             }
 92         }
 93 
 94         ProduceService pros = new ProduceService();
 95         ImgService is = new ImgService();
 96 
 97         // 存储商品信息并添加主键信息
 98         try {
 99             pros.add(pro);
100             // 存储图片
101             for (Img i : list) {
102                 i.setProduceId(pro.getId());
103                 is.save(i);
104             }
105             request.setAttribute("message", "上传成功");
106             request.getRequestDispatcher("index.jsp")
107                     .forward(request, response);
108         } catch (Exception e) {
109             request.setAttribute("message", "上传失败");
110             request.getRequestDispatcher("index.jsp")
111                     .forward(request, response);
112             e.printStackTrace();
113         }
114 
115     }
116 
117 }