使用IDEA maven 开发
jar包
<!-- 上传图片 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
配置spring配置文件
只截取相关部分
<!-- 3.定义视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 视图转换(指定格式)-->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 1024 * 1024 * 20 = 20M -->
<property name="maxUploadSize" value="20971520"/>
<property name="maxInMemorySize" value="20971520"/>
</bean>
前端相关代码
使用spring mvc提供的form表单,此处必需添加该标签:enctype="multipart/form-data"
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">缩略图</div>
<div class="item-input">
<input type="file" name="shop-img">
</div>
</div>
</div>
</li>
Controller 代码
@RequestMapping("/add")
public String add(Shop shop, @RequestParam("shop-img")MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
CommonsMultipartFile shopImg = null;
if (file != null){
shopImg = (CommonsMultipartFile)file;
} else {
System.out.println("shopImg is null");
// 提示上传图片... TODO
}
if (shop != null && shopImg != null){
try {
shopExecution = shopBiz.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
} catch (IOException e) {
//
e.printStackTrace();
}
}else {
// ...
}
}
service 层接收文件流,存储到目标文件中