Spring MVC 上传图片

使用IDEA maven 开发

jar包
		<!-- 上传图片 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
配置spring配置文件

只截取相关部分

	<!-- 3.定义视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 视图转换(指定格式)-->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 1024 * 1024 * 20 = 20M -->
        <property name="maxUploadSize" value="20971520"/>
        <property name="maxInMemorySize" value="20971520"/>
    </bean>
前端相关代码

使用spring mvc提供的form表单,此处必需添加该标签:enctype="multipart/form-data"

<li>
    <div class="item-content">
        <div class="item-inner">
            <div class="item-title label">缩略图</div>
                <div class="item-input">
                    <input type="file" name="shop-img">
                </div>
           </div>
     </div>
</li>
Controller 代码
	@RequestMapping("/add")
    public String add(Shop shop, @RequestParam("shop-img")MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
    	CommonsMultipartFile shopImg = null;
        
    	if (file != null){
        	shopImg = (CommonsMultipartFile)file;
    	} else {
            	System.out.println("shopImg is null");
            	// 提示上传图片... TODO
        }

        if (shop != null && shopImg != null){
	         try {
                shopExecution = shopBiz.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
            } catch (IOException e) {
                //
                e.printStackTrace();
            }
        }else {
        	// ...
       	}
    }

service 层接收文件流,存储到目标文件中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值