SpringMvc文件上传

需要的jar包

commons-fileupload-1.2.1.jar

commons-io-2.2.jar




index.jsp

 <form action="C/upload.do" method="post" enctype="multipart/form-data">

  文件:<input type="file" name="img">

 上传: <input type="submit" value="上传">


控制器

CController.java

package controller;

import java.io.File;
import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/C")
public class CController {
   @RequestMapping(value="index")
    public String index(){
        return "index";
    }
     @RequestMapping(value="upload.do")
     /*
      * 这里的参数名一定要跟文件上传中的 file name名称一致
      * 否则需要加@RequestParam  

      */
    public String upload(MultipartFile img){
        String path="E:/image";
        //获得文件的原始路径
        String filename = img.getOriginalFilename();
        System.out.println("文件原始路径="+filename);
        String[] paths = filename.split("[.]");
        filename=paths[0]+"-"+System.currentTimeMillis()+"."+paths[1];
        System.out.println(filename);
        File file=new File(path, filename);
        try {

              //把传过来的img图片通过的流的方式写入指定的路径

            img.transferTo(file);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/loadsuccess";
    }
}



最后在xxx-servlet.xml配置支持文件上传的 MultipartResolver

<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

注意需要在xxx-servlet.xml中配置支持mvc注解驱动

  <mvc:annotation-driven/>








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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值