springmvc如何上传图片

本文介绍在Spring MVC框架下如何配置虚拟路径映射真实路径,实现文件上传功能。详细展示了配置过程,包括使用commons-fileupload和commons-io库,springmvc.xml中的multipartResolver配置,jsp页面的图片展示代码,以及controller中的文件处理逻辑。

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

eclispe中配置虚拟路径配置

 

 上图的真实路径是D:\images\2.jpg

 

jar包

commons-fileupload.jar和commons-io.jar

springmvc.xml中的配置


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

 

jsp中的代码

<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="picture"/> 
	</td>
</tr>

controller中的代码

public String editItemSubmit(Model model,Integer id,
 @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,
			//上传图片
			MultipartFile picture
			)throws Exception{
		
	
		//进行图片上传
		if(picture!=null && picture.getOriginalFilename()!=null && picture.getOriginalFilename().length()>0){
			//图片上传成功后,将图片的地址写到数据库
			String filePath = "D:\\images\\";
			//上传文件原始名称
			String originalFilename = picture.getOriginalFilename();
			//新的图片名称
			String newFileName = UUID.randomUUID() +originalFilename.substring(originalFilename.lastIndexOf("."));
			//新文件
			File file = new java.io.File(filePath+newFileName);
			
			//将内存中的文件写入磁盘
			picture.transferTo(file);
			
			//图片上传成功,将新图片地址写入数据库
			itemsCustom.setPic(newFileName);
		}
		
	
		//调用service接口更新商品信息
		itemsService.updateItems(id, itemsCustom);

		//转发
		return "forward:queryItems.action";
	}
	

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值