簡介 SpringMvc文件上傳的實現,是由commons-fileupload這個jar包實現的。 需求 在修改商品頁面,添加上傳商品圖片功能。 Maven依賴包 pom.xml <!-- 文件上傳 --> <dependency> <groupId>commons-fileupload</gro ...
簡介
SpringMvc文件上傳的實現,是由commons-fileupload這個jar包實現的。
需求
在修改商品頁面,添加上傳商品圖片功能。
Maven依賴包
pom.xml
<!-- 文件上傳 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
配置多部件bean:springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 處理器類的掃描 --> <context:component-scan base-package="com.cyb.ssm.controller"></context:component-scan> <mvc:annotation-driven conversion-service="conversionService" /> <!-- 顯示配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置自定義的轉換服務 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <!-- 自定義日期類型轉換器 --> <bean class="com.cyb.ssm.controller.converter.DateConverter"></bean> </set> </property> </bean> <!-- 配置異常處理器 --> <bean class="com.cyb.ssm.resolver.CustomExceptionResolver"></bean> <!-- 配置多部件解析器,id固定值,不能亂寫 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 限制上傳文件的大小,單位是byte --> <property name="maxUploadSize" value="5000000"></property> </bean> </beans>
控制層:ItemController.java
package com.cyb.ssm.controller; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.cyb.ssm.exception.CustomException; import com.cyb.ssm.po.Item; import com.cyb.ssm.po.ItemQueryVO; import com.cyb.ssm.service.ItemService; //@Controller //RestController:註解相當於Controller註解和ResponseBody註解的結合體 @RestController @RequestMapping(value = "item", produces = "application/json;charset=utf8") public class ItemController { @Autowired private ItemService Service; @RequestMapping(value = "updateItem") public Item updateItem(Integer id, String name, Float price, Item item, MultipartFile pictureFile) throws Exception { System.out.println("1111"); if (pictureFile != null) { //獲取上傳文件名稱 String originalFilename = pictureFile.getOriginalFilename(); if (originalFilename != null && !"".contentEquals(originalFilename)) { //獲取擴展名 String extName = originalFilename.substring(originalFilename.lastIndexOf(".")); //重新生成一個文件名稱 String newFileName = UUID.randomUUID().toString()+extName; //指定存儲文件的根目錄 String baseDir="D:\\temp\\pic\\"; File dirFile=new File(baseDir); if (!dirFile.exists()) { dirFile.mkdirs(); } //將上傳的文件複製到新的文件(完整路徑)中 pictureFile.transferTo(new File(baseDir + newFileName)); //保存文件路徑 item.setPic(newFileName); } } //商品修改 Service.updateItem(item); return item; } @RequestMapping("showEdit") public ModelAndView showEdit(Integer id) { Item item = Service.queryItemById(id); ModelAndView mvAndView = new ModelAndView(); mvAndView.addObject("item", item); mvAndView.setViewName("item/item-edit"); return mvAndView; } }
jsp文件:item-edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>修改商品信息</title> </head> <body> <!-- 上傳圖片是需要指定屬性 enctype="multipart/form-data" --> <form id="itemForm" action="${pageContext.request.contextPath}/item/updateItem" method="post" enctype="multipart/form-data"> <input type="hidden" name="id" value="${item.id }" /> 修改商品信息: <table width="100%" border=1> <tr> <td>商品名稱</td> <td><input type="text" name="name" value="${item.name }" /></td> </tr> <tr> <td>商品價格</td> <td><input type="text" name="price" value="${item.price }" /></td> </tr> <tr> <td>商品圖片</td> <td><c:if test="${item.pic !=null}"> <img src="http://localhost/pic/${item.pic} " width=100 height=100 /> <br /> </c:if> <input type="file" name="pictureFile" /></td> </tr> <tr> <td>商品簡介</td> <td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea> </td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="提交" /> </td> </tr> </table> </form> </body> </html>