SpringMVC 图片上传

//图片上传首先要导入相应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的参数绑定名一致。
以上,就是整个图片上传的流程及代码。

猜你喜欢

转载自blog.csdn.net/past__time/article/details/77601290