springmvc的文件的上传

在新建项目之前导入样式和jsp页面:
1.把样式的文件夹放在web下面
2.把jsp页面放在web/WEB-INF下面

项目中需要导入的jar包
在这里插入图片描述

1.首先配置web.xml文件:

在这里插入<servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>

        <!--配置文件上传的初始化信息-->
        <multipart-config>
            <location>D:/yangyang</location><!--临时上传目录-->
            <max-file-size>5242880</max-file-size><!--5MB--><!--上传文件的大小-->
            <max-request-size>20971520</max-request-size><!--20MB--><!--请求含有的mulipart数据的大小-->
            <file-size-threshold>0</file-size-threshold><!--写入数据的阈值-->
        </multipart-config>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>代码片
  

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.java12.demo"></context:component-scan>

     <mvc:annotation-driven></mvc:annotation-driven>

    <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>

    <!--配置multpart的处理器 在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 cintext
        它会自动寻找在上下文中定义的一个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(用于创建包含MultiparFile的文件对象)

在这里插入代public class FileBucket {
    private MultipartFile file;
    public MultipartFile getFile(){
        return file;
    }
    public void setFile(MultipartFile file){
        this.file=file;
    }
}码片

4.写已给验证器的类FileValidator.java

在这里插入import com.java12.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;
    }

    /*Error用于存放错误信息*/
    @Override
    public void validate(Object o, Errors errors) {
        FileBucket file= (FileBucket) o;
        MultipartFile multipartFile = file.getFile();

        if(multipartFile!=null){
            if(multipartFile.getSize()==0){
                /*放置错误信息  用于前台<form:error>信息展示*/
                errors.rejectValue("file","missing.file");
            }
        }

    }
}代码片

5.控制器类FileUploadController.java

在这里插入代package com.java12.demo.controller;

import com.java12.demo.entity.FileBucket;
import com.java12.demo.validator.FileValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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;
import java.io.InputStream;

@Controller
public class FileUploadController {

    private static String UPLOAD_LOCATION="D:/myyangyang/";

    @Autowired
    private FileValidator fileValidator;

    /*添加文件的验证器*/
    @InitBinder
    public void initSingleFileValidator(WebDataBinder webDataBinder){
        webDataBinder.addValidators(fileValidator);
    }

    @RequestMapping(value = {"/","welcome"})
    public String welcome(){
        return "welcome";
    }


    /*
    * 渲染springmvc的表单
    * 1.首先form表单中得使用modelAttribute 从request作用域中取出域对象
    * 2.在跳转form表单中的处理方法中往request作用域中添加域对象
    * 3.该域对象中的属性必须得与form表单中path属性一一对应
    * */
    @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方式了
    * */

/*此处是从Errors接口中的子类即BindingResult中取出在验证器存放的错误信息*/
    @PostMapping("singleUpload")
    public String singleFileUpload(@Valid FileBucket fileBucket, BindingResult result, Model model) throws IOException {
        if(result.hasErrors()){
            System.out.println("validation errors");
            return "singleFileUploader";
        }else {
            System.out.println("Fetching file");
            MultipartFile file = fileBucket.getFile();
            String name = file.getName();
            System.out.println("输入的文件名为:"+name);
            String filename1 = file.getOriginalFilename();
            System.out.println("输入文件的原始文件名"+filename1);
            String contentType = file.getContentType();
            System.out.println("文件类型:"+contentType);
            String s = new String(file.getBytes());
            System.out.println(s);


            MultipartFile multipartFile = fileBucket.getFile();
            FileCopyUtils.copy(fileBucket.getFile().getBytes(), new File(UPLOAD_LOCATION + fileBucket.getFile().getOriginalFilename()));
            String filename = multipartFile.getOriginalFilename();
            model.addAttribute("fileName",filename);
            return "success";
        }

    }

}
码片
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值