文件上传(springmvc)

1.web.xml



    
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        
        
            D:/tmp
            5242880  
            20971520 
            0
        

    
    
        dispatcher
        /
    

2.dispatcher-servlet.xml



    
    
   

    
        
        
    
    
    
    
    
    
    
    
        
        
    

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){
               // 放置错误信息 用于前台信息展示
                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=请选择一个文件

 

你可能感兴趣的:(java,springmvc,文件上传)