SpringMVC之文档图片上传

一.Jsp页面

<form name="Form" action="/SpringMVC/upateItem" method="post"  enctype="multipart/form-data">
<tr>  
<td>商品图片</td>  
<td>  
    <c:if test="${itemsCustom.pic !=null}">  
        <img src="/pic/${itemsCustom.pic}" width=100 height=100/>  
        <br/>  
    </c:if>  
    <input type="file"  name="itemsPic"/>   
</td>  
</tr>
</form> 

二、spring-mvc.xml配置文件上传解析器

<!-- 文件上传,id必须设置为multipartResolver -->
<!-- 定义文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设定默认编码 -->
    <property name="defaultEncoding" value="UTF-8"></property>
    <!-- 设定文件上传的最大值为5MB,5*1024*1024 -->
    <property name="maxUploadSize" value="5242880"></property>
    <!-- 设定文件上传时写入内存的最大值,如果小于这个参数不会生成临时文件,默认为10240 -->
    <property name="maxInMemorySize" value="40960"></property>
    <!-- 上传文件的临时路径 -->
    <property name="uploadTempDir" value="fileUpload/temp"></property>
    <!-- 延迟文件解析 -->
    <property name="resolveLazily" value="true"/>
</bean>

三、Controller控制器接收itemsPic参数

@RequestMapping("updateItem")
public String updateItemById(Item item, MultipartFile itemsPic) throws Exception {
	// 图片上传
	// 设置图片名称,不能重复,可以使用uuid
	String picName = UUID.randomUUID().toString();

	// 获取文件名
	String oriName = itemsPic.getOriginalFilename();
	// 获取图片后缀
	String extName = oriName.substring(oriName.lastIndexOf("."));

	// 开始上传
	itemsPic.transferTo(new File("C:/upload/image/" + picName + extName));

	// 设置图片名到商品中
	item.setPic(picName + extName);
	// ---------------------------------------------
	// 更新商品
	this.itemService.updateItemById(item);

	return "forward:/itemEdit.action";
}

猜你喜欢

转载自blog.csdn.net/mmake1994/article/details/85404838