springMVC上传文件

1. 添加依赖

<!--  用于处理文件上传 commons-fileupload 依赖于 commons-io 来处理文件和流操作
    主要功能包括:
    处理文件上传请求:解析 multipart/form-data 请求,提取文件和表单字段。
    文件存储:将上传的文件存储在磁盘或内存中。
    文件信息获取:获取上传文件的名称、大小、类型等信息。
-->
      <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
      </dependency>
<!--  用于简化 IO 操作
    主要功能包括:
    文件操作:复制、移动、删除文件和目录。
    流操作:读取和写入流,简化流的操作。
    文件过滤:根据文件名、扩展名等过滤文件。
-->
      <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
      </dependency>
    </dependencies>

2. 配置类

        因为我的uploadFile.html文件放在WEB-INF/目录下,所以配置InternalResourceViewResolver,对请求进行解析。

@Configuration
@EnableWebMvc // 开启Spring MVC的注解驱动
@ComponentScan(basePackages = "com.huan.web") // 扫描Controller包
public class WebConfig implements WebMvcConfigurer {
    /**
     * 访问 webapp下的静态资源
     * 配置默认的servlet处理器
     * @param configurer
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    /**
     * 访问web-inf目录下的静态资源
     * 视图解析器 配置路径匹配规则
     * @return
     */
    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        return resolver;
    }


    /**
     * 添加拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //将一个新的 MyInterceptor 实例添加到拦截器注册表中, 并指定拦截器的拦截路径为 "/**"
        //"/**" 表示拦截所有路径。** 是一个通配符,表示任意数量的字符和子路径。
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }

    //配置文件上传解析器
    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setDefaultEncoding("UTF-8");
        multipartResolver.setMaxUploadSize(1024 * 1024 * 30);//设置上传文件大小为30M
        multipartResolver.setMaxUploadSizePerFile(1024 * 1024 * 10);//设置单个上传文件大小为10M
        return multipartResolver;
    }
}

3. 前端界面(同步)


    <h1>文件上传(同步)</h1>
    <form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="上传">
    </form>

4. 前端界面(异步:vue+axios)


    <h1>文件上传(异步)</h1>
    <div id="app">
        <form>
            <input type="file" @change="handle">
            <input type="button" @click="uploadFile" value="上传">
        </form>
    </div>

    <script src="static/js/vue.js"></script>
    <script src="static/js/jquery-1.9.1.js"></script>
    <script src="static/js/axios.js"></script>
    <script type="text/javascript">
        let vm = new Vue({
            el: '#app',
            data: {
                file: ''
            },
            methods: {
                handle:function (e) {
                    //设置file
                    this.file = e.target.files[0];
                },
                uploadFile:function () {
                    //设置表单对象
                    let formData = new FormData();
                    formData.append('file', this.file);
                    axios.post('upload', formData, {
                        headers: {
                            'Content-Type':'multipart/form-data' //设置请求头,配置表单数据类型
                        }
                    }).then(response =>{
                        alert(response.data);
                    }).catch(error => {
                        console.log(error);
                    });
                }
            }
        });
    </script>

5. 控制类

@Controller
public class UploadFileController {
    @ResponseBody
    @PostMapping("/upload")
    public void upload(
            @RequestParam("file") //作用是获取前端表单中name为file的文件
            MultipartFile file){
        if (!file.isEmpty()){
            try{
                //获取文件名
                String fileName = file.getOriginalFilename();
                //设置文件保存路径
                String filePath = "path/to/save/"+fileName;
                System.out.println(filePath);
                //保存文件
                file.transferTo(new File(filePath));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    @RequestMapping("/uploadFile")
    public String uploadFile() {
        return "uploadFile";
    }
}

6. 启动tomcat

0. 请求界面

1. 测试同步

测试成功,页面发生跳转,同时日志中显示文件成功上传到指定的目录下。

2. 测试异步

测试成功,页面没有发生跳转,同时日志中显示文件成功上传到指定的目录下。

tips:

这里的使用的日志是logback,同时指定了特别关注的包中的日志信息,具体的配置可以看http://t.csdnimg.cn/k44xDicon-default.png?t=N7T8http://t.csdnimg.cn/k44xD

并且使用springmvc的拦截器记录了请求日志,具体使用可以看http://t.csdnimg.cn/k44xDicon-default.png?t=N7T8http://t.csdnimg.cn/k44xD

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

睆小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值