javaEE Springmvc,檔案(圖片)上傳
阿新 • • 發佈:2018-12-11
需要額外匯入檔案上傳的Jar包:commons-io和commons-fileupload的Jar包
ItemController.java(Controller後端控制器,檔案上傳(接收檔案型別的引數)):
package com.xxx.springmvc.controller; import java.io.File; import java.util.UUID; import org.apache.commons.io.FilenameUtils; //需要匯入commons-io和commons-fileupload的Jar包 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import com.xxx.springmvc.pojo.QueryVo; import com.xxx.springmvc.service.ItemService; //商品管理 @Controller @RequestMapping(value = "/item") public class ItemController { @Autowired private ItemService itemService; //接收請求引數(檔案型別) @RequestMapping(value = "/updateItem.action") //public String updateitem(QueryVo vo,MultipartFile pictureFile) throws Exception { public String updateitem(MultipartFile pictureFile) throws Exception { //MultipartFile表示接收前端file表單元素的檔案;形參pictureFile要和file元素的name屬性值相同。 String name = UUID.randomUUID().toString().replaceAll("-", ""); //獲取上傳檔案的字尾名。 jpg String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename()); //將圖片儲存到指定位置。 pictureFile.transferTo(new File("D:\\upload\\" + name + "." + ext)); //.................... return "redirect:/itemlist.action"; } }
src/springmvc.xml(Springmvc的核心配置檔案,配置檔案上傳解析器):
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 開啟註解掃描。 掃描 @Controler @Service等註解 --> <context:component-scan base-package="com.xxx"/> <!-- 註解驅動; 指定處理器對映器、處理器介面卡 --> <mvc:annotation-driven /> <!-- 配置檔案上傳解析器;id必須設定為"multipartResolver" --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 可以限制上傳圖片的大小 單位B --> <property name="maxUploadSize" value="5000000" /> <!-- 大約5M大小 --> </bean> <!-- 檢視解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <!-- 檢視(jsp頁面)請求路徑的字首 --> <property name="suffix" value=".jsp"/> <!-- 字尾 --> </bean> </beans>