SpringMVC 图片上传

本文详细讲解了如何使用SpringMVC框架实现图片上传功能,包括配置web.xml、定义上传控制器Bean以及处理文件上传的步骤。通过实例代码解析,帮助读者掌握SpringMVC中的文件上传操作。

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

//图片上传首先要导入相应jar包,然后配置web.xml文件,代码如下:
<!-- 支持上传文件  -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        //设置文件的上传尺寸最大5MB
        <property name="maxUploadSize" value="5242880"/>    
    </bean>
//其次,在页面form表单提交的时候, enctype = "multipart/form-data"的类型的数据时,需要对multipart类型的数据进行解析。
//紧接着创建图片上传的虚拟路径,可直接修改tomcat的配置,在conf/server.xml文件中,添加虚拟目录:<Context docBase="F:develop\upload\temp" path="/pic" reloadable="false" privileged="true"/>

//在Controller成接受图片类型的文件需要用 MultipartFile的类型来接受,参数绑定名为items_pic.
//下面是上传图片的Controller代码:
//原始名称
    String originalFileName = items_pic.getOriginalFileName();
if(items_pic != null && originalFileName != null && originalFileName.length >0){
    //存储图片的物理路径
    String pic_path = "F:\\develop\\upload\\temp\\";
    //新的图片名称
    String newFileName = UUID.randomUUID() +originalFileName.substring(originalFileName.lastIndexOf("."));
    //新图片
    File newFile = new File(pic_path + newFileName);
    //将内存中的数据写入磁盘
    items_pic.transferTo(newFile);
    //之后将生成的newFileName set到相对应的实体类里面。
}
//接下来是页面的代码,如下:
<tr>
    <td>商品名称</td>
    <td>
        <c:if test="${items.pic != null}">
        <img src="/pic/${items.pic}" width=100 height=100/>
        <br/>
        </if>
        <input type = "file" name="items_pic"/>
    </td>
</tr>

//注意:input标签中的name属性的值,一定要是同Controller的参数绑定名一致。
以上,就是整个图片上传的流程及代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值