SpringBoot实战学习(五) SpringMVC高级配置1:文件上传

1.目录结构

SpringBoot实战学习(五) SpringMVC高级配置1:文件上传_第1张图片

2.编写

  1. pom.xml添加上传文件依赖
      
      <dependency>
          <groupId>commons-fileuploadgroupId>
          <artifactId>commons-fileuploadartifactId>
          <version>1.3.1version>     
      dependency>
       
      <dependency>
          <groupId>commons-iogroupId>
          <artifactId>commons-ioartifactId>
          <version>2.3version>     
      dependency>

2.上传页面
在src/main/resource/views下新建upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>upload pagetitle>
head>
<body>
      <div class="upload">
          <form action="upload" enctype="multipart/form-data" method="post">
              <input type="file" name="file"><br>
              <input type="submit" value="上传">
          form>
      div>
body>
html>

3.MyMvcConfig添加转向到upload页面的ViewController和MultipartResolver

package com.wen.springmvc4;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.wen.springmvc4.interceptor.DemoInterceptor;



/**
 * Spring MVC配置
 * @author EGWri
 *
 */
@Configuration//声明当前类是一个配置类
@EnableWebMvc//开启默认配置,开启SpringMVC支持(无此句重写WebMvcConfigurerAdapter方法无效)
@ComponentScan("com.wen.springmvc4")//自动扫描包名下所有使用@Service、@Component、@Repository和@Controller的类,并注册为Bean
//继承WebMvcConfigurerAdapter类,重写其方法可对SpringMVC进行配置
public class MyMvcConfig extends WebMvcConfigurerAdapter{

    @Bean
    public InternalResourceViewResolver viewResolver(){
        //SpringMVC渲染核心,映射路径和实际页面的位置
        InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");//表示路径前缀(运行时目录结构)
        viewResolver.setSuffix(".jsp");//表示路径后缀,假设 ViewName 为 hello,则完整路径为 /WEB-INF/page/hello.jsp
        viewResolver.setViewClass(JstlView.class);//viewClass: 表示要解析的视图类型
        return viewResolver;
        }

        /**静态目录**/
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
        }   //addResourceHandler对外暴露的路径,addResourceLocations文件放置的目录
        /**静态目录**/

        /**拦截器  **/
        @Bean//配置拦截器的Bean
        public DemoInterceptor demoInterceptor(){
            return new DemoInterceptor();
        }

        @Override//重写addInterceptors方法,注册拦截器
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(demoInterceptor());
        }
        /**拦截器  **/

        /**页面转向 ,简化代码量**/
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/toUpload").setViewName("/upload");
        }
        /**页面转向  **/

        /**MultipartResolver 上传文件**/
        @Bean
        public MultipartResolver multipartResolver(){
            CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver();
            multipartResolver.setMaxUploadSize(1000000);
            return multipartResolver;
        }
        /**MultipartResolver**/
}

4.控制器

package com.wen.springmvc4.web;

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

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadConroller {

    @RequestMapping(value="/upload",method=RequestMethod.POST)
    //@ResponseBody支持将返回值放在response体内,而不是返回一个页面。可放在返回值前或者方法上
    public @ResponseBody String upload(MultipartFile file){//使用MultipartFile接受上传的文件
        try{//使用FileUtils.writeByteArrayToFile快速写文件到磁盘
            FileUtils.writeByteArrayToFile(new File("E:/upload/"+file.getOriginalFilename()), file.getBytes());
            return "ok";
        }catch (IOException e) {
            e.printStackTrace();
            return "wrong";
        }
    }

}

3.运行

将程序部署到Tomcat,运行,访问http://localhost:8080/SpringMVC/toUpload
SpringBoot实战学习(五) SpringMVC高级配置1:文件上传_第2张图片
单击“上传按钮”,查看E:\upload文件夹
SpringBoot实战学习(五) SpringMVC高级配置1:文件上传_第3张图片

你可能感兴趣的:(SpringBoot)