SpringMVC-图片上传

本文介绍如何在Spring MVC框架中实现图片上传功能,包括配置multipart解析器限制文件大小、前端表单设置及后端控制器处理流程。文章还提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在springmvc.xml中配置multipart类型解析器 

	<!-- 配置multipart类型解析器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置上传文件的最大尺寸为5MB -->
		<property name="maxUploadSize">
			<value>5242880</value>
		</property>
	</bean>

导入上传图片的jar包

form表单代码

<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="${itemsCustom.id }"/>
修改商品信息:
<table width="100%" border=1>
<tr>
	<td>商品名称</td>
	<td><input type="text" name="itemsCustom.name" value="${itemsCustom.name }"/></td>
</tr>
<tr>
	<td>商品价格</td>
	<td><input type="text" name="itemsCustom.price" value="${itemsCustom.price }"/></td>
</tr>
<tr>
	<td>商品生产日期</td>
	<td><input type="text" name="itemsCustom.createtime" value="<fmt:formatDate value="${itemsCustom.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
</tr>
<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="items_pic"/> 
	</td>
</tr>
<tr>
	<td>商品简介</td>
	<td>
	<textarea rows="3" cols="30" name="itemsCustom.detail">${itemsCustom.detail }</textarea>
	</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>

controller代码

	//商品信息修改提交
	@RequestMapping("/editItemsSubmit")
	public String editItemsSubmit(Integer id,ItemsQueryVo itemsQueryVo,MultipartFile items_pic) throws Exception{
		
		
		//存储图片的物理路径
		String pic_path = "F:\\SpringMVC_PROJ\\SpringMVC_pic\\";
		//图片文件的原始名
		String pictureFile_name = items_pic.getOriginalFilename();
		
		if(items_pic != null && pictureFile_name != null && pictureFile_name.length()>0){
			//图片文件的新名称
			String newFileName = UUID.randomUUID().toString() + pictureFile_name.substring(pictureFile_name.lastIndexOf("."));
			//新图片
			File newFile = new File(pic_path+newFileName);
			//将内存中的数据写入磁盘
			items_pic.transferTo(newFile);
			//将新的图片名称写入itemsQueryVo
			itemsQueryVo.getItemsCustom().setPic(newFileName);
		}
		
		//修改ItemsCustom
		itemsService.updateItems(id, itemsQueryVo);
		
		//使用转发,转发到商品列表页面
		return "forward:queryItems.action";
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值