SpringMVC(15)——文件上传

概述

Spring MVC框架的文件上传是基于commons-fileupload组件的文件上传。

因此所需要的包是commons-fileupload.jar和commons-io.jar包。

基于表单的文件上传

<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile"/>
</form>

对于基于表单的文件上传,必须要entype属性并且将其值设置为multipart/form-data,同时表单的提交方式是post。

表单的enctype属性指定的是表单数据的编码方式,该属性有以下3个值:

  • application/x-www-form-urlencoded:这是默认的编码方式,它只处理表单域里的
    value属性值。
  • multipart/form-data:该编码方式以二进制流的方式来处理表单数据,并将文件域指
    定文件的内容封装到请求参数里。
  • text/plain:该编码方式只有当表单的action属性为mailto:URL的形式时才使用,主
    要适用于直接通过表单发送邮件的方式。

MultipartFile接口

在SpringMVC中上传文件时将文件相关信息及操作封装到MultipartFile对象中,因此只需要使用MultipartFile类型声明模型类的一个属性即可对被上传文件进行操作。

该接口有如下方法:

  • byte[] getBytes():以字节数组的形式返回文件的内容。
  • String getContentType():返回文件的内容类型。
  • InputStream getInputStream():返回一个InputStream,从中读取文件的内容。
  • String getName():返回请求参数的名称
  • String getOriginalFilename():返回客户端提交的原始文件的名称
  • long getSize():返回文件的大小,单位为字节。
  • boolean isEmpty():判断被上传文件是否为空。
  • void transferTo(File destination):将上传文件保存到目标目录下。

在上传文件时需要在配置文件中配置MultipartResolver用于上传文件。

单文件上传

项目所需用到的jar包

创建springmvc项目并按照如下图创建文件夹及文件

各文件内容如下:

FileUploadController.java

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.UploadFile;

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

@Controller
public class FileUploadController {
    /**
     * 单文件上传
     */
    @RequestMapping("/upload")
    public String upload(@ModelAttribute UploadFile uploadFile, HttpServletRequest request) {
        // 文件上传到服务器的位置"/fileUpload/temp/"
        String realPath = request.getServletContext().getRealPath("/fileUpload/temp/");
        System.out.println("文件所在位置:" + realPath);
        String originalFilename = uploadFile.getMyfile().getOriginalFilename();
        File targetFile = new File(realPath, originalFilename);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 上传
        try {
            uploadFile.getMyfile().transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}

UploadFile.java

package pojo;

import org.springframework.web.multipart.MultipartFile;

public class UploadFile {
    // 声明一个MultipartFile类型的属性封装被上传的文件信息,属性名与文件选择页面index.jsp中的file类型的表单参数名myfile相同
    private MultipartFile myfile;

    public MultipartFile getMyfile() {
        return myfile;
    }

    public void setMyfile(MultipartFile myfile) {
        this.myfile = myfile;
    }
}

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>成功</title>
</head>
<body>
<%--${uploadFile.myfile.originalFilename}等同于uploadFile.getMyfile().getOriginalFilename()--%>
<h1><span style="color:#FF0000;">${uploadFile.myfile.originalFilename}</span>文件上传成功</h1>
</body>
</html>

springmvc-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:p="http://www.springframework.org/schema/p"
       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">

    <!-- 使用扫描机制,扫描包 -->
    <context:component-scan base-package="controller"/>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--使用Spring的CommonsMultipartResolver配置MultipartResolver用于文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" p:maxUploadSize="5400000" p:uploadTempDir="fileUpload/temp">
        <!--defaultEncoding="utf-8"是请求的编码格式,默认是iso-8859-1;maxUploadSize="5400000"是允许上传文件的最大值,单位为字节;uploadTempDir="fileUpload/temp"为上传文件的临时路径-->
    </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 避免中文乱码 -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="myfile"><br>
    <input type="submit" value="上传文件">
</form>
</body>
</html>

运行程序效果如下:

点击【浏览】按钮选择想要上传的文件,点击【上传文件】按钮上传文件

可以看到上传成功的文件

 

如果对完整源码有兴趣。

可搜索微信公众号【Java实例程序】或者扫描下方二维码关注公众号获取更多。

注意:在公众号后台回复【CSDN201911181402】可获取本节源码。

多文件上传

多文件上传其实只是单文件上传的循环遍历而已。

创建springmvc项目并按照下图创建文件及文件夹

各文件内容如下:

FileUploadController.java

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import pojo.UploadFile;

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

@Controller
public class FileUploadController {
    /**
     * 多文件上传
     */
    @RequestMapping("/upload")
    public String upload(@ModelAttribute UploadFile uploadFile, HttpServletRequest request) {
        // 文件上传到服务器的位置"/fileUpload/temp/"
        String realPath = request.getServletContext().getRealPath("/fileUpload/temp/");
        System.out.println("文件所在位置:" + realPath);
        File targetDir=new File(realPath);
        if(!targetDir.exists()){
            targetDir.mkdirs();
        }
        List<MultipartFile> files=uploadFile.getMyfile();
        for (int i = 0; i < files.size(); i++) {
            MultipartFile multipartFile = files.get(i);
            String originalFilename = multipartFile.getOriginalFilename();
            File targetFile=new File(realPath,originalFilename);
            // 上传文件
            try {
                multipartFile.transferTo(targetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "success";
    }
}

UploadFile.java

package pojo;

import org.springframework.web.multipart.MultipartFile;

import java.util.List;

public class UploadFile {
    // 声明一个MultipartFile类型的属性封装被上传的文件信息,属性名与文件选择页面index.jsp中的file类型的表单参数名myfile相同
    private List<MultipartFile> myfile;

    public List<MultipartFile> getMyfile() {
        return myfile;
    }

    public void setMyfile(List<MultipartFile> myfile) {
        this.myfile = myfile;
    }
}

success.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>成功</title>
</head>
<body>
<%--${uploadFile.myfile.originalFilename}等同于uploadFile.getMyfile().getOriginalFilename()--%>
<ul>
    <c:forEach items="${uploadFile.myfile}" var="file">
        <li style="color: red">${file.originalFilename}</li>
    </c:forEach>
</ul>
</body>
</html>

springmvc-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:p="http://www.springframework.org/schema/p"
       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">

    <!-- 使用扫描机制,扫描包 -->
    <context:component-scan base-package="controller"/>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--使用Spring的CommonsMultipartResolver配置MultipartResolver用于文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" p:maxUploadSize="5400000" p:uploadTempDir="fileUpload/temp">
        <!--defaultEncoding="utf-8"是请求的编码格式,默认是iso-8859-1;maxUploadSize="5400000"是允许上传文件的最大值,单位为字节;uploadTempDir="fileUpload/temp"为上传文件的临时路径-->
    </bean>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- 避免中文乱码 -->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
    选择文件1:<input type="file" name="myfile"><br>
    选择文件2:<input type="file" name="myfile"><br>
    选择文件3:<input type="file" name="myfile"><br>
    选择文件4:<input type="file" name="myfile"><br>
    选择文件5:<input type="file" name="myfile"><br>
    <input type="submit" value="上传文件">
</form>
</body>
</html>

运行项目程序,效果如下

点击【浏览】选择需要上传的文件,点击【上传文件】进行上传文件。

上传成功的结果如下:

查看文件

 

如果对完整源码有兴趣。

可搜索微信公众号【Java实例程序】或者扫描下方二维码关注公众号获取更多。

注意:在公众号后台回复【CSDN201911181448】可获取本节源码。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值