文件上传(springmvc)

1.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--配置文件上传的初始化信息-->
        <multipart-config>
            <location>D:/tmp</location><!--临时上传的目录-->
            <max-file-size>5242880</max-file-size><!--5MB-->  <!--上传文件的大小-->
            <max-request-size>20971520</max-request-size> <!--20MB--><!--请求包含multipart数据的大小-->
            <file-size-threshold>0</file-size-threshold><!--写入数据的阈值-->
        </multipart-config>

    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2.dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.java.smvc.demo"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>
   <!-- <mvc:default-servlet-handler></mvc:default-servlet-handler>-->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--处理具体目录下的静态资源-->
    <mvc:resources mapping="/static/**" location="/static/"></mvc:resources>
    <!-- 配置multipart的处理器 在servlet3.0以上的容器中运行 不依赖其他的jar包项目-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>
    <!--
       When an ApplicationContext is loaded,
       //当ApplicationContext被加载的时候
       it automatically searches for a MessageSource bean defined in the context.
       //它会自动寻找在上下文中定义的一个MessageSource bean
       The bean must have the name messageSource
       //这个bean的名字必须定义为messageSource
   -->
    <!--配置国际化资源处理-->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
</beans>

3.FileBucket   构建包含MultipartFile的文件对象

package com.java.smvc.demo.entity;

import org.springframework.web.multipart.MultipartFile;

/**
 * 构建包含MultipartFile的文件对象
 */
public class FileBucket {
    private MultipartFile file;

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }
}

4.FileValidator   文件验证器

package com.java.smvc.demo.validator;

import com.java.smvc.demo.entity.FileBucket;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.multipart.MultipartFile;
@Component
public class FileValidator implements Validator {
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
    //Errors 用于存放错误信息
    @Override
    public void validate(Object o, Errors errors) {
        FileBucket file =(FileBucket) o;
        MultipartFile multipartFile = file.getFile();
        if (multipartFile!=null){
            if (multipartFile.getSize()==0){
               // 放置错误信息 用于前台<form:errors>信息展示
                errors.rejectValue("file","missing.file");
            }
        }
    }
}

5.FileUploadController    控制器

package com.java.smvc.demo.controller;

import com.java.smvc.demo.entity.FileBucket;

import com.java.smvc.demo.validator.FileValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

@Controller
public class FileUploadController {
    private static String UPLOAD_LOCATION="D:/mytemp/";
    @Autowired
    private FileValidator fileValidator;
    /*添加文件验证器*/
    @InitBinder
    public void initSingleFileValidator(WebDataBinder binder){
        binder.addValidators(fileValidator);
    }
    @RequestMapping(value = {"/","welcome"})
    public String welcome(){
        return "welcome";
    }

    /**
     * 渲染springmvc 的表单
     * 1,首先 form表单中得使用modelAttribute 从request作用域中取出域对象
     * 2,在跳转form表单的处理方法中往request作用域中添加域对象
     * 3,该域对象中的属性必须得与form表单中的path属性名一一对应
     * @param model
     * @return
     */
    //@RequestMapping(value = "singleUpload")
    @GetMapping(value = "singleUpload")
    public String singleUpload(Model model){
        FileBucket fileBucket = new FileBucket();
        model.addAttribute("fileBucket",fileBucket);
        return "singleFileUploader";
    }

    /**
     * singleFileUploader 页面由welcome.jsp中的get请求链接singleUpload 发送过来
     * 所以在表单未什么action的前提下,还会回到原来的请求中去即singleUpload 只是请求方式变为了post请求
     * @return
     *
     */
    //@Valid 用于验证该对象 错误信息是存放在FileValidator类的validate方法中的Errors接口中。
    //此处从Errors接口的子类即BindingResult中取出在验证器存放的错误信息
    @PostMapping("singleUpload")
    public String singleFileUpload(@Valid FileBucket fileBucket,
                                   BindingResult result, ModelMap model) throws IOException, IOException {

        if (result.hasErrors()) {
            System.out.println("validation errors");
            return "singleFileUploader";
        } else {
            System.out.println("Fetching file");
            MultipartFile multipartFile = fileBucket.getFile();
            System.out.println("MultipartFile对象:"+multipartFile);
            System.out.println("原始文件名字:"+multipartFile.getOriginalFilename());
            System.out.println("文件的类型:"+multipartFile.getContentType());
            String str = new String(multipartFile.getBytes());
            System.out.println("读取文件内容为:"+str);

            // 使用springmvc提供的文件复制工具类 将文件复制到指定的目录中去
            FileCopyUtils.copy(fileBucket.getFile().getBytes(), new File( UPLOAD_LOCATION + fileBucket.getFile().getOriginalFilename()));
            String fileName = multipartFile.getOriginalFilename();
            model.addAttribute("fileName", fileName);
            return "success";
        }
}}

6.提示信息

messages.properties

missing.file=Please select a file

messages_en_US.properties

missing.file=Please select a file

 messages_zh_CN.properties

missing.file=请选择一个文件

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值