ssm上传文件

ssm上传文件(上传到本地磁盘)

(1)先要导入所需要的jar包或者pom文件中添加依赖

    <!-- 上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

(2)在springMVC文件中添加配置

  <!-- 定义文件上传解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设定默认编码 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>

(3)上传到本地磁盘

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" value="file" name="file">
    <input type="submit" value="提交">
</form>
@RequestMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile file) throws Exception, IOException {
        //获取上传文件的类型
        String contentType = file.getContentType();
        System.out.println(contentType);
        if(contentType.contains("application/x-msdownload")) {
            return "fail";
        }
        //获取原始的文件名
        String oldName = file.getOriginalFilename();
        System.out.println(oldName);
        //获取文件扩展名
        String ex = oldName.substring(oldName.lastIndexOf(".")+1);
        System.out.println(ex);
        //生成新的文件名
        String newFile =UUID.randomUUID()+"."+ex;
        System.out.println(newFile);
        //创建年月日三级目录
        String dateFolder="";
        if(!file.isEmpty()) {
            dateFolder = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        }
        //文件保存的路径
        String filePath="D:\upload\"+dateFolder+"/"+newFile;
        //如果没有 自动创建文件夹
        File f = new File("D:\upload\"+dateFolder);
        if(!f.exists()) {
            f.mkdirs();
        }
        //上传 将文件保存到磁盘
        file.transferTo(new File(filePath));
        return "success";
    }
原文地址:https://www.cnblogs.com/wanerhu/p/11000483.html