栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC入门宝典(六)SpringMVC文件上传(上)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC入门宝典(六)SpringMVC文件上传(上)

目录

一.原生方式上传

二.SpringMVC方式上传

三.上传多文件


一.原生方式上传 上传是 Web 工程中很常见的功能, SpringMVC 框架简化了文件上传的代码,我们首先使用 JAVAEE 原生方式上传文件: 创建一个子模块 1 (1)创建新的 SpringMVC 项目(即上面的子模块),在 web.xml 中将项目从 2.3 改为 3.1 , 即可默 认开启 el 表达式 ,修改web.xml内容如下:

  Archetype Created Web Application

并把上个子模块的pom.xml里的依赖和插件复制到这个子模块中。

pom.xml:




  4.0.0

  com.first
  mvc_demo2
  1.0-SNAPSHOT
  war

  mvc_demo2 Maven Webapp
  
  http://www.example.com

  
    
    
      org.springframework
      spring-context
      5.2.12.RELEASE
    
    
    
      org.springframework
      spring-web
      5.2.12.RELEASE
    
    
    
      org.springframework
      spring-webmvc
      5.2.12.RELEASE
    
    
    
      javax.servlet
      servlet-api
      2.5
      
      provided
    
    
    
      javax.servlet.jsp
      jsp-api
      2.0
      provided
    
    
    
      com.fasterxml.jackson.core
      jackson-core
      2.9.0
    
    
      com.fasterxml.jackson.core
      jackson-databind
      2.9.0
    
    
      com.fasterxml.jackson.core
      jackson-annotations
      2.9.0
    
  
  
    
      
      
        org.apache.tomcat.maven
        tomcat7-maven-plugin
        2.1
        
          8080
          /
          UTF-8
          tomcat7
          
            %1$tH:%1$tM:%1$tS %2$s%n%4$s: %5$s%6$s%n
            
          
        
      
    
  

springmvc.xml:




        
        
    
    

    
    
        
        
        
        
    

    
    

然后web.xml再添加一些上个子工程的一些配置 ,


  Archetype Created Web Application

  
  
    encFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      utf-8
    
  
  
    encFilter
    /*
  

  
  
    httpMethodFilter
    org.springframework.web.filter.HiddenHttpMethodFilter
  
  
    httpMethodFilter
    
    /*
  

  
  
    dispatcherServlet
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      
      classpath:springmvc.xml
    
    
    1
  
  
    dispatcherServlet
    
    /
  

(2)编写上传表单

upload.jsp:

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


    上传


文件上传
<%-- 文件上传控件,类型是file --%> 选择文件:

然后如下创建:

package com.first.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

@Controller
public class UploadController {
    @RequestMapping("/fileUpload")
    public String upload(HttpServletRequest request) throws Exception {
        // 获取输入流
        ServletInputStream is = request.getInputStream();
        // 从输入流获取请求体数据
        int i = 0;
        while ((i=is.read())!=-1){
            System.out.print((char)i);
        }
        return "index";
    }
}

访问 http://localhost:8080/upload.jsp

 控制台部分输出如下:

(3)接收请求体数据:

接下来需要分析请求体中的文件项,并将数据写入磁盘,此时需要借助文件上传工具 (1)引入文件上传依赖:


    commons-fileupload
    commonsfileupload
    1.3.1
 
    commons-io
    commons-io
    2.4
(2)编写控制器接收上传请求,控制器进行三步操作:
  1. 创建文件夹,存放上传文件。
  2. 分析请求体,找到上传文件数据。
  3. 将文件数据写入文件夹。
package com.first.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@Controller
public class UploadController {
    //原生上传方式
    @RequestMapping("/fileUpload")
    public String upload(HttpServletRequest request) throws Exception {
        // 创建文件夹,存放上传文件
        // 1.设置上传文件夹的真实路径
        String realPath = request.getSession().getServletContext().getRealPath("/upload");

        // 2.判断该目录是否存在,如果不存在,创建该目录
        File file = new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }

        // 分析请求体,找到上传文件数据
        // 1.创建磁盘文件工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 2.创建上传数据分析器对象
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        // 3.利用分析器对象解析请求体,返回所有数据项
        List fileItems = servletFileUpload.parseRequest(request);
        // 4.遍历所有数据,找到文件项(非表单项)
        for (FileItem fileItem:fileItems){
            if(!fileItem.isFormField()){
                // 将文件数据写入文件夹
                // 1.获取文件名
                String name = fileItem.getName();
                // 2.将文件写入磁盘
                fileItem.write(new File(file,name));
                // 3.删除内存中的临时文件
                fileItem.delete();
            }
        }
        return "index";
    }
}

访问http://localhost:8080/upload.jsp

二.SpringMVC方式上传 SpringMVC 使用框架提供的文件解析器对象,可以直接将请求体中的文件数据转为 MultipartFile 对象,从而省略原生上传中分析请求 体的步骤。 1 1.在 SpringMVC 核心配置文件配置文件解析器


    
    
    
    

2.创建JSP表单upload2.jsp

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



    上传


文件上传
<%-- 文件上传控件,类型是file --%> 选择文件:

3.编写控制器接收上传请求

// MultipartFile参数名必须和JSP文件空间的name属性一致
    @RequestMapping("/fileUpload2")
    public String upload2(MultipartFile file, HttpServletRequest request) throws IOException {
        // 创建文件夹,存放上传文件
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
        File dir = new File(realPath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        // 将上传的数据写到文件夹的文件中
        // 1.拿到上传的文件名
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID()+"_"+filename;
        // 2.创建空文件
        File newFile = new File(dir,filename);
        // 3.将数据写入空文件中
        file.transferTo(newFile);
        //视图解析器,跳转到index.jsp页面
        return "index";
    }

访问http://localhost:8080/upload2.jsp

 选择一个文件上传,比如一张图片,然后自动跳转到index.jsp页面中

 然后查看webapp目录下,自动创建了upload文件夹,且此文件夹下有上传的图片。

三.上传多文件 SpringMVC 支持一次性上传多个文件,写法如下: 1 up 1.创建 JSP 表单 upload3.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    上传


文件上传
<%-- 文件上传控件,类型是file --%> 用户名: 选择文件: 选择文件:

2.编写控制器接收上传请求

@RequestMapping("/fileUpload3")
    public String upload3(String username,MultipartFile[] files,HttpServletRequest request) throws IOException {
        System.out.println(username);

        // 创建文件夹,存放上传文件
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
        File dir = new File(realPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        // 遍历数组,将上传的文件保存到文件夹
        for (MultipartFile file : files) {
            String filename = file.getOriginalFilename();
            filename = UUID.randomUUID()+"_"+filename;
            File newFile = new File(dir, filename);
            file.transferTo(newFile);
        }
        return "index";
    }

访问:http://localhost:8080/upload3.jsp

 点击上传

 控制台输出:

 查看webapp下upload文件夹

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005596.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号