spring mvc 上传开发流程

一、导入对应依赖(用到contorller还要另外导入servlet的依赖)

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<--这个是commons-io自带的servlet-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
    <exclusions>
        <exclusion>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

二、设置表单

<form action="${pageContext.request.contextPath }/upload/test1" method="post" 
      enctype="multipart/form-data">
  file: <input type="file" name="source"/> <br>
  <input type="submit" value="提交"/>
</form>

    三要素

1.表单请求必须为post

2.上传格式 enctype="multipart/form-data"

3.上传input 中type属性为"file"

三、配置上传解析器(id必须为multipartResolver)

<!--    上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760"></property><!--上传文件的最大大小-->
        <property name="maxUploadSizePerFile" value="1048576"/><!--单个文件的最大大小-->
        <property name="defaultEncoding" value="utf0-8"/> <!--上传文件的编码-->
    </bean>

四、Contorller

@Controller
public class UploadController {

    @RequestMapping("/upload")
    public String upload(MultipartFile file, HttpSession session){

        //获得文件的原生名字
        String filename = file.getOriginalFilename();
        //分割文件名
        String prefix = filename.split("\\.")[0];
        String suffix = filename.split("\\.")[1];
        System.out.println(prefix);
        System.out.println(suffix);

        //加上UuId
        String random = UUID.randomUUID().toString();

        String fileName=prefix+random+"."+suffix;

        String path = session.getServletContext().getRealPath("/upload");
        File file1 = new File(path);
        //如果文件不存在则自动创建文件路径下的文件夹
        if(!file1.exists()){
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(path,fileName));//将文件数据写入硬盘
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "index";
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值