SpringMVC的文件上传

1.创建项目,完善结构,导入依赖,配置web.xml

<!-- 配置开发SpringMVC所以来的jar包 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.1.5.RELEASE</version>
</dependency>
<!-- 配置ServletAPI依赖 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
  <scope>provided</scope>
</dependency>
<!-- commons-fileupload组件 -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>

2.创建SpringMVC配置文件

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--配置自动扫描包-->
    <context:component-scan base-package="com.wangxing.springmvc.controller"></context:component-scan>
    <!-- 视图解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--maxUploadSize上传文件的大小  -->
        <property name="maxUploadSize" value="104857600" />
        <!--maxInMemorySize内存大小 -->
        <property name="maxInMemorySize" value="4096" />
        <!--defaultEncoding默认字符编码 -->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
</beans>

3.创建文件上传页面下载页面,和成功的页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传页面</title>
</head>
<body>
<!--
     1.form表单的method属性一定是post
     2.enctype属性一定要设置且取值multipart/form-data
      enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码
      application/x-www-form-urlencoded----在发送前编码所有字符(默认)
      multipart/form-data----不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
      text/plain---空格转换为 "+" 加号,但不对特殊字符编码。
     3.文件上传控件---<input type="file" name="myfile">
  -->
<form action="upload.do" method="post" enctype="multipart/form-data">
    <input type="file" name="myfile"><br>
    <input type="submit" value="上传">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件下载页面</title>
</head>
<body>
<h4><a href="dowload.do?myfile=Spring框架(6).docx">下载MW150UM 2.0.zip</a></h4>
<h4><a href="dowload.do?myfile=Spring框架(5).docx">下载SpringBoot.docx</a></h4>
<h4><a href="dowload.do?myfile=福岛圣水.jpg">下载捕获.PNG</a></h4>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>文件上传成功</h1>
</body>
</html>

4.创建处理文件上传请求的控制器和下载请求控制器

package com.wangxing.springmvc.fileup.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

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

@Controller
public class UpLoadController {
    @RequestMapping(value = "upload.do", method = RequestMethod.POST)
    public ModelAndView upLoad(HttpServletRequest request) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        //处理包含有文件的http请求
        //1.将当前类中的ServletContext对象转换成CommonsMultipartResolver
        ServletContext servletContext = request.getSession().getServletContext();
        //利用CommonsMultipartResolver构造方法将ServletContext对象转换为CommonsMultipartResolver对象
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(servletContext);
        //2.检验HttpServletRequest是否是一个文件上传请求
        if (commonsMultipartResolver.isMultipart(request)) {
            //3.将HttpServletRequest请求转换成文件上传请求[强制类型转换]
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            //4.从文件上传请求中得到文件名称
            Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
            while (fileNames.hasNext()) {
                //得到input元素的name属性
                String nameshuxing = fileNames.next().toString();
                //根据name属性值得到上传来的文件对象
                MultipartFile file = multipartHttpServletRequest.getFile(nameshuxing);
                //保存上传来的文件对象
                String zhenFileName = "";
                if (file != null) {
                    //得到被上传来的文件的真实名称[test.html]
                    zhenFileName = file.getOriginalFilename();
                    //获取项目的根目录
                    String realPath = servletContext.getRealPath("/upload");
                    //创建保存文件的目录
                    File uploadpicdir = new File(realPath);
                    if (!uploadpicdir.exists()) {
                        //创建upload目录
                        uploadpicdir.mkdirs();
                    }
                    //组织一个保存文件的对象[文件保存目录+文件名称]
                    String pathfile = uploadpicdir.getAbsolutePath() + File.separator + zhenFileName;
                    System.out.println(pathfile);
                    File saveFile = new File(pathfile);
                    //保存文件到本地磁盘
                    file.transferTo(saveFile);
                }
                //得到上传成功以后的文件的http访问路径
                String reqURL = request.getRequestURI().toString();
                System.out.println("reqURL=="+reqURL);
                reqURL = reqURL.substring(0,reqURL.lastIndexOf("/"));
                reqURL = reqURL+"/upload"+zhenFileName;
                //http://127.0.0.1:8080/upload/xxxxxx.jpg
                System.out.println("reqURL=="+reqURL);
            }
            modelAndView.setViewName("success.html");
        }
        return modelAndView;
    }
}
package com.wangxing.springmvc.fileup.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
public class DownloadController {
    @RequestMapping("/download.do")
    public ResponseEntity<byte[]> downloadMethod(HttpServletRequest request)throws Exception{
        //filename====MW150UM 2.0.zip
        String filename = request.getParameter("myfile");
        //realPath====F:/20201201/apache-tomcat-8.0.52/webapps/demo9/upload
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
        //创建保存文件的目录的文件对象
        File uploadpicdir = new File(realPath);
        //F:/20201201/apache-tomcat-8.0.52/webapps/demo9/upload/MW150UM 2.0.zip
        File file = new File(uploadpicdir,filename);
        if(file.exists()){
            //设置http协议头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment",filename);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
        }
        return null;
    }
}

5.部署测试

   SpringMVC的文件上传

http://localhost:8080/FileUpLoading_war/upload.html

SpringMVC的文件下载

http://localhost:8080/FileUpLoading_war/download.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值