为何我的upload文件夹里面总是空的?
我可以正常添加商品和商品图片,也可以在database里看到添加的文件名和path,但是成功添加后我的Upload文件夹是空的。 多谢帮忙。
这是我的UploadUtil:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | package com.imooc.utils; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * 鏂囦欢涓婁紶鐨勫伐鍏风被 * */ public class UploadUtils { /** * generate unique filename so that no file gets a same name */ public static String getUUIDFileName(String fileName) { // get part of the filename xx.jpg ---> .jpg int idx = fileName.lastIndexOf( "." ); String extention = fileName.substring(idx); String uuidFileName = UUID.randomUUID().toString().replace( "-" , "" ) + extention; return uuidFileName; } public static Map uploadFile(HttpServletRequest request) throws IOException { Map<String, String> map = new HashMap<String, String>(); // 1.create a disk file factory DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // 2.创建一个核心解析类 ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // 3.解析request请求,返回的是list集合,list集合中存放的是FileItem对象 String url = null ; String uuidFileName = null ; try { List<FileItem> list = servletFileUpload.parseRequest(request); for (FileItem fileItem : list) { // 是表单项,但不是文件上传 if (fileItem.isFormField()) { // 接收表单项参数的值: String name = fileItem.getFieldName(); // 获得表单项的name属性的值 String value = fileItem.getString( "UTF-8" ); // 获得表单项的值 // 存入集合 map.put(name, value); // 文件上传项 } else { // 获得文件上传的名称 String fileName = fileItem.getName(); System.out.println( "filename=" + fileName); if (fileName != null && ! "" .equals(fileName)) { // 通过工具类获得唯一文件名: uuidFileName = UploadUtils.getUUIDFileName(fileName); // 获得文件上传的数据: InputStream is = fileItem.getInputStream(); // 获得文件上传的路径: String path = request.getServletContext().getRealPath( "/upload" ); // 将输入流对接到输出流就可以了: url = path + "\\" + uuidFileName; OutputStream os = new FileOutputStream(url); int len = 0 ; byte [] b = new byte [ 1024 ]; while ((len = is.read(b)) != - 1 ) { os.write(b, 0 , len); } is.close(); os.close(); map.put( "path" , request.getContextPath() + "/upload/" + uuidFileName); map.put( "filename" , fileName); } System.out.println(map); } } } catch (FileUploadException e) { e.printStackTrace(); } return map; } public static void main(String[] args) { System.out.println(getUUIDFileName( "1.jpg" )); } } |
这是我的商品的DAO代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | package com.imooc.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import com.imooc.dao.ProductDao; import com.imooc.domain.Product; import com.imooc.utils.JDBCUtils; public class ProductDaoImpl implements ProductDao { @Override public List<Product> findAll() { // init Connection conn = null ; PreparedStatement pstmt = null ; ResultSet rs = null ; List<Product> list = null ; try { // get conn conn = JDBCUtils.getConnection(); // write sql String sql = "SELECT * FROM product p, category c WHERE p.cid = c.cid ORDER BY p.pid DESC" ; // preprocess sql pstmt = conn.prepareStatement(sql); // execute rs = pstmt.executeQuery(); // handle result list = new ArrayList<Product>(); while (rs.next()) { // encapsulation each result into product Product product = new Product(); product.setPid(rs.getInt( "pid" )); product.setAuthor(rs.getString( "author" )); product.setDescription(rs.getString( "description" )); product.setFilename(rs.getString( "filename" )); product.setPath(rs.getString( "path" )); product.setPname(rs.getString( "pname" )); product.setPrice(rs.getDouble( "price" )); // encapsulation the category to which the product belong product.getCategory().setCid(rs.getInt( "cid" )); product.getCategory().setCname(rs.getString( "cname" )); product.getCategory().setCdesc(rs.getString( "cdesc" )); // add the product into list list.add(product); } } catch (Exception e) { e.printStackTrace(); } finally { // release resources JDBCUtils.release(rs, pstmt, conn); } return list; } @Override public void save(Product product) { // init Connection conn = null ; PreparedStatement pstmt = null ; try { // get conn conn = JDBCUtils.getConnection(); // write sql String sql = "INSERT INTO product VALUES(null, ?, ?, ?, ?, ?, ?, ?)" ; // preprocess sql pstmt = conn.prepareStatement(sql); // fill sql pstmt.setString( 1 , product.getPname()); pstmt.setString( 2 , product.getAuthor()); pstmt.setDouble( 3 , product.getPrice()); pstmt.setString( 4 , product.getDescription()); pstmt.setString( 5 , product.getFilename()); pstmt.setString( 6 , product.getPath()); pstmt.setInt( 7 , product.getCategory().getCid()); // execute pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { // release JDBCUtils.release(pstmt, conn); } } @Override public Product findOne(Integer pid) { // init Connection conn = null ; ResultSet rs = null ; PreparedStatement pstmt = null ; try { // get conn conn = JDBCUtils.getConnection(); // write sql String sql = "SELECT * FROM product p, category c WHERE p.cid = c.cid AND p.pid = ?" ; // preprocess sql pstmt = conn.prepareStatement(sql); // fill sql params pstmt.setInt( 1 , pid); // execute rs = pstmt.executeQuery(); // handle result if (rs.next()) { // encapsulation Product product = new Product(); product.setPid(rs.getInt( "pid" )); product.setPname(rs.getString( "pname" )); product.setAuthor(rs.getString( "author" )); product.setPrice(rs.getDouble( "price" )); product.setDescription(rs.getString( "description" )); product.setFilename(rs.getString( "filename" )); product.setPath(rs.getString( "path" )); product.getCategory().setCid(rs.getInt( "cid" )); product.getCategory().setCname(rs.getString( "cname" )); product.getCategory().setCdesc(rs.getString( "cdesc" )); return product; } } catch (Exception e) { e.printStackTrace(); } finally { // release JDBCUtils.release(rs, pstmt, conn); } return null ; } @Override public void update(Product product) { // init Connection conn = null ; PreparedStatement pstmt = null ; int rs = 0 ; try { // get conn conn = JDBCUtils.getConnection(); // write sql String sql = "UPDATE product SET pname = ?, author = ?, price = ?, description = ?, filename = ?, path = ?, cid = ? WHERE pid = ?" ; // preprocess sql pstmt = conn.prepareStatement(sql); // fill sql pstmt.setString( 1 , product.getPname()); pstmt.setString( 2 , product.getAuthor()); pstmt.setDouble( 3 , product.getPrice()); pstmt.setString( 4 , product.getDescription()); pstmt.setString( 5 , product.getFilename()); pstmt.setString( 6 , product.getPath()); pstmt.setInt( 7 , product.getCategory().getCid()); pstmt.setInt( 8 , product.getPid()); // execute rs = pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { // release JDBCUtils.release(pstmt, conn); } } @Override public void delete(Integer pid) { // init Connection conn = null ; PreparedStatement pstmt = null ; try { // get conn conn = JDBCUtils.getConnection(); // write sql String sql = "DELETE FROM product WHERE pid = ?" ; // preprocess sql pstmt = conn.prepareStatement(sql); // fill sql pstmt.setInt( 1 , pid); // execute pstmt.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { // release JDBCUtils.release(pstmt, conn); } } } |
这是我的ProductServlet代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | package com.imooc.web.action; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.imooc.domain.Category; import com.imooc.domain.Product; import com.imooc.service.CategoryService; import com.imooc.service.ProductService; import com.imooc.service.Impl.CategoryServiceImpl; import com.imooc.service.Impl.ProductServiceImpl; import com.imooc.utils.UploadUtils; /** * Servlet implementation class ProductServlet */ @WebServlet ( "/ProductServlet" ) public class ProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get method String methodName = request.getParameter( "method" ); if ( "findAll" .equals(methodName)) { try { findAll(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ( "saveUI" .equals(methodName)) { try { saveUI(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ( "save" .equals(methodName)) { try { save(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ( "edit" .equals(methodName)) { try { edit(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ( "update" .equals(methodName)) { try { update(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ( "delete" .equals(methodName)) { try { delete(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * delete a product on backend * * @param request * @param response * @throws Exception */ private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception { // get params Integer pid = Integer.parseInt(request.getParameter( "pid" )); // call service ProductService productService = new ProductServiceImpl(); // find one product(to delete the picture saved) Product product = productService.findOne(pid); String path = product.getPath(); if (path != "" && path != null ) { // get the absolute disk path String realPath = this .getServletContext().getRealPath(path); System.out.println(realPath); File file = new File(realPath); if (file.exists()) { file.delete(); } } productService.delete(pid); // redirect page response.sendRedirect(request.getContextPath() + "/ProductServlet?method=findAll" ); } /** * update a product en backend * * @param request * @param response * @throws Exception */ private void update(HttpServletRequest request, HttpServletResponse response) throws Exception { // get params Map<String, String> map = UploadUtils.uploadFile(request); // encapsulation Product product = new Product(); product.setPid(Integer.parseInt(map.get( "pid" ))); product.setPname(map.get( "pname" )); product.setAuthor(map.get( "author" )); product.setPrice(Double.parseDouble(map.get( "price" ))); product.setDescription(map.get( "description" )); product.setFilename(map.get( "filename" )); product.setPath(map.get( "path" )); product.getCategory().setCid(Integer.parseInt(map.get( "cid" ))); // call service ProductService productService = new ProductServiceImpl(); productService.update(product); // redirect response.sendRedirect(request.getContextPath() + "/ProductServlet?method=findAll" ); } /** * edit product on backend * * @param request * @param response * @throws Exception * @throws ServletException */ private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, Exception { // get params Integer pid = Integer.parseInt(request.getParameter( "pid" )); // call service to find product in database ProductService productService = new ProductServiceImpl(); Product product = productService.findOne(pid); // find all category CategoryService categoryService = new CategoryServiceImpl(); List<Category> CategoryList = categoryService.findAll(); // set product in request attribute request.setAttribute( "product" , product); request.setAttribute( "categoryList" , CategoryList); // redirect request to edit page request.getRequestDispatcher( "/admin/product_update.jsp" ).forward(request, response); } /** * save adding a product * * @param request * @param response * @throws Exception */ private void save(HttpServletRequest request, HttpServletResponse response) throws Exception { // upload file Map<String, String> map = UploadUtils.uploadFile(request); // encapsule data Product product = new Product(); product.setPname(map.get( "pname" )); product.setAuthor(map.get( "author" )); product.setPrice(Double.parseDouble(map.get( "price" ))); product.setDescription(map.get( "description" )); product.setFilename(map.get( "filename" )); product.setPath(map.get( "path" )); product.getCategory().setCid(Integer.parseInt(map.get( "cid" ))); // handle into database ProductService productService = new ProductServiceImpl(); productService.save(product); // redirect response.sendRedirect(request.getContextPath() + "/ProductServlet?method=findAll" ); } /** * redirect to add product page * * @param request * @param response * @throws Exception * @throws ServletException */ private void saveUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, Exception { // find out all categories CategoryService categoryService = new CategoryServiceImpl(); List<Category> list = categoryService.findAll(); // redirect request.setAttribute( "categoryList" , list); request.getRequestDispatcher( "/admin/product_add.jsp" ).forward(request, response); } /** * find all products * * @param request * @param response * @throws Exception */ private void findAll(HttpServletRequest request, HttpServletResponse response) throws Exception { // call the service ProductService productService = new ProductServiceImpl(); List<Product> list = productService.findAll(); // redirect request.setAttribute( "list" , list); request.getRequestDispatcher( "/admin/product_list.jsp" ).forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } |
以及我的Produc_add.jsp:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> < html > <!-- Mirrored from admindesigns.com/demos/absolute/1.1/admin_forms-validation.html by HTTrack Website Copier/3.x [XR&CO'2014], Thu, 06 Aug 2015 02:56:15 GMT --> < head > <!-- Meta, title, CSS, favicons, etc. --> < meta charset = "utf-8" > < title >油画商城--添加商品</ title > < link rel = "stylesheet" type = "text/css" href = "${pageContext.request.contextPath }/assets/skin/default_skin/css/theme.css" > < link rel = "stylesheet" type = "text/css" href = "${pageContext.request.contextPath }/assets/admin-tools/admin-forms/css/admin-forms.css" > < link rel = "shortcut icon" href = "${pageContext.request.contextPath }/assets/img/favicon.ico" > </ head > < body class = "admin-validation-page" data-spy = "scroll" data-target = "#nav-spy" data-offset = "200" > < div id = "main" > <%@ include file="header.jsp" %> <%@ include file="left.jsp" %> < section id = "content_wrapper" > < section id = "content" class = "table-layout animated fadeIn" > < div class = "tray tray-center" > < div class = "content-header" > < h2 > 添加商品 </ h2 > < p class = "lead" ></ p > </ div > < div class = "admin-form theme-primary mw1000 center-block" style = "padding-bottom: 175px;" > < div class = "panel heading-border" > <!-- 文件上传的要素: 1.表单的提交方式必须是POST; 2.表单中有文件上传项目,必须有name和对应的值; 3.表单的属性enctype属性需要设置为multipart/form-data; 文件上传使用的是apach的fileUpload组件。接受参数不能用getPrameter接受input hidden的参数,但是可以在action里面直接写参数。 --> < form id = "admin-form" name = "addForm" action = "${pageContext.request.contextPath}/ProductServlet?method=save" method = "post" enctype = "multipart/form-data" > < div class = "panel-body bg-light" > < div class = "section-divider mt20 mb40" > < span > 基本信息 </ span > </ div > < div class = "section row" > < div class = "col-md-2" ></ div > < div class = "col-md-1" > < label for = "sn" class = "field prepend-icon" > < label for = "sn" class = "field-icon" > 名称 </ label > </ label > </ div > < div class = "col-md-6" > < label for = "sn" class = "field" > < input name = "pname" class = "gui-input" placeholder = "名称" type = "text" value = "" /> </ label > </ div > </ div > < div class = "section row" > < div class = "col-md-2" ></ div > < div class = "col-md-1" > < label for = "sn" class = "field prepend-icon" > < label for = "sn" class = "field-icon" > 价格 </ label > </ label > </ div > < div class = "col-md-6" > < label for = "sn" class = "field" > < input name = "price" class = "gui-input" placeholder = "价格" type = "text" value = "" /> </ label > </ div > </ div > < div class = "section row" > < div class = "col-md-2" ></ div > < div class = "col-md-1" > < label for = "sn" class = "field prepend-icon" > < label for = "sn" class = "field-icon" > 作者 </ label > </ label > </ div > < div class = "col-md-6" > < label for = "sn" class = "field" > < input name = "author" class = "gui-input" placeholder = "作者" type = "text" value = "" /> </ label > </ div > </ div > < div class = "section row" > < div class = "col-md-2" ></ div > < div class = "col-md-1" > < label for = "sn" class = "field prepend-icon" > < label for = "sn" class = "field-icon" > 分类 </ label > </ label > </ div > < div class = "col-md-6" > < label for = "sn" class = "field select" > < select id = "departmentSn" name = "cid" class = "gui-input" placeholder = "分类..." > < c:forEach var = "category" items = "${categoryList}" > < option value = "${category.cid}" >${category.cname}</ option > </ c:forEach > </ select > < i class = "arrow double" ></ i > </ label > </ div > </ div > < div class = "section row" > < div class = "col-md-2" ></ div > < div class = "col-md-1" > < label for = "sn" class = "field prepend-icon" > < label for = "sn" class = "field-icon" > 图片 </ label > </ label > </ div > < div class = "col-md-6" > < label for = "name" class = "field" > < input id = "name" name = "filename" class = "gui-input" type = "file" value = "" /> </ label > </ div > </ div > < div class = "section row" > < div class = "col-md-2" ></ div > < div class = "col-md-1" > < label for = "sn" class = "field prepend-icon" > < label for = "sn" class = "field-icon" > 描述 </ label > </ label > </ div > < div class = "col-md-6" > < label for = "address" class = "field" > < input name = "description" class = "gui-input" placeholder = "描述" type = "text" value = "" /> </ label > </ div > </ div > < div class = "panel-footer text-center" > < button type = "submit" class = "button" > 保存 </ button > < button type = "button" class = "button" onclick = "javascript:window.history.go(-1);" > 返回 </ button > </ div > </ div > </ form > </ div > </ div > </ div > </ section > </ section > </ div > < style > /* demo page styles */ body { min-height: 2300px; } .content-header b, .admin-form .panel.heading-border:before, .admin-form .panel .heading-border:before { transition: all 0.7s ease; } /* responsive demo styles */ @media (max-width: 800px) { .admin-form .panel-body { padding: 18px 12px; } } </ style > < style > .ui-datepicker select.ui-datepicker-month, .ui-datepicker select.ui-datepicker-year { width: 48%; margin-top: 0; margin-bottom: 0; line-height: 25px; text-indent: 3px; color: #888; border-color: #DDD; background-color: #FDFDFD; -webkit-appearance: none; /*Optionally disable dropdown arrow*/ } </ style > < script src = "vendor/jquery/jquery-1.11.1.min.js" ></ script > < script src = "vendor/jquery/jquery_ui/jquery-ui.min.js" ></ script > < script src = "assets/admin-tools/admin-forms/js/jquery.validate.min.js" ></ script > < script src = "assets/admin-tools/admin-forms/js/additional-methods.min.js" ></ script > < script src = "assets/admin-tools/admin-forms/js/jquery-ui-datepicker.min.js" ></ script > < script src = "assets/js/utility/utility.js" ></ script > < script src = "assets/js/demo/demo.js" ></ script > < script src = "assets/js/main.js" ></ script > < script type = "text/javascript" src = "js/pages.js" ></ script > < script type = "text/javascript" src = "js/items.js" ></ script > </ body > </ html > |
4
收起
正在回答 回答被采纳积分+1
1回答
3. Java 数据库开发与实战应用
- 参与学习 人
- 提交作业 357 份
- 解答问题 8016 个
本阶段将带你学习MySQL数据库,JDBC接口,MyBatis框架等,带你掌握的数据的存放和管理。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧