初学SpringMVC之文件上传和下载

pom.xml 文件导入 commons-fileupload 的 jar 包

        <!-- 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.5</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

index.jsp:

enctype="multipart/form-data"

浏览器会采用二进制流的方式来处理表单数据

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>

		<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
			<input type="file" name="file"/>
			<input type="submit" value="upload"/>
		</form>

	</body>
</html>

Spring MVC 为文件上传提供了直接的支持

上传文件配置,固定写法

    <!-- 文件上传配置 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 请求的编码格式,必须和JSP的pageEncoding属性一致,默认为ISO-8859-1 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>

方法一:通过 IO 流

package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class FileController {
    //@RequestParam("file") 将 name=file 控件得到的文件封装成 CommonsMultipartFile 对象
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //获取文件名:file.getOriginalFilename()
        String uploadFileName = file.getOriginalFilename();

        //如果文件名为空,返回到首页
        if("".equals(uploadFileName)){
            return "redirect:/index.jsp";
        }
        System.out.println("上传文件名:" + uploadFileName);

        //上传路径保存设置
        String path = request.getSession().getServletContext().getRealPath("/upload");

        //如果路径不存在,创建一个
        File realPath = new File(path);
        if(!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址:" + realPath);

        InputStream inputStream = file.getInputStream(); //文件输入流
        FileOutputStream outputStream = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流

        //读取写出
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = inputStream.read(buffer)) != -1){
            outputStream.write(buffer,0,len);
            outputStream.flush();
        }

        outputStream.close();
        inputStream.close();

        return "redirect:/index.jsp";

    }
}

方法二:通过 file.transferTo 来保存上传的文件

package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

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

@Controller
public class FileController {
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException {

        //上传路径保存设置
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if(!realPath.exists()){
            realPath.mkdir();
        }

        //上传文件地址
        System.out.println("上传文件保存地址:" + realPath);

        //通过 CommonsMultipartFile 方法直接写文件
        file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));

        return "redirect:/index.jsp";

    }
}

可以看到目录生成,上传的文件将出现在文件夹

下载文件:

1.设置 response 响应头

2.读取文件 InputStream

3.写出文件 OutputStream

4.执行操作

5.关闭流,先开后关

package com.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
public class FileController {
    @RequestMapping(value = "/download")
    public String download(HttpServletRequest request,HttpServletResponse response) throws Exception {

        //要下载的文件地址
        String path = request.getSession().getServletContext().getRealPath("/upload");
        String fileName = ""; //填文件名

        //1.设置 response 响应头
        response.reset(); //设置页面不缓存,清空 buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        //设置响应头
        response.setHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(fileName,"UTF-8"));

        File file = new File(path, fileName);

        //2.读取文件 输入流
        InputStream input = new FileInputStream(file);

        //3.写出文件 输出流
        OutputStream output = response.getOutputStream();

        byte[] buffer = new byte[1024];
        int index = 0;

        //4.执行 写出操作
        while (index = input.read(buffer) != -1){
            output.write(buffer,0,index);
            output.flush();
        }

        //5.关闭流 先开后关
        output.close();
        input.close();

        return null;
        
    }
}

相关推荐

  1. SpringMVC文件下载

    2024-07-20 10:48:01       70 阅读
  2. SpringMVC11、文件下载

    2024-07-20 10:48:01       45 阅读
  3. SpringMVC-文件下载

    2024-07-20 10:48:01       56 阅读
  4. SpringMVC文件

    2024-07-20 10:48:01       47 阅读
  5. springMVC-文件

    2024-07-20 10:48:01       68 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-20 10:48:01       104 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-20 10:48:01       115 阅读
  3. 在Django里面运行非项目文件

    2024-07-20 10:48:01       94 阅读
  4. Python语言-面向对象

    2024-07-20 10:48:01       100 阅读

热门阅读

  1. 高并发小结

    2024-07-20 10:48:01       24 阅读
  2. linux学习笔记整理: 关于linux:nginx服务器 2024/7/20;

    2024-07-20 10:48:01       27 阅读
  3. 初等数论精解【1】

    2024-07-20 10:48:01       24 阅读
  4. Base64编码与解码

    2024-07-20 10:48:01       30 阅读
  5. Android Studio关于Gradle及JDK问题解决

    2024-07-20 10:48:01       25 阅读
  6. Oracle(12)什么是主键(Primary Key)?

    2024-07-20 10:48:01       25 阅读
  7. 目标检测算法

    2024-07-20 10:48:01       23 阅读
  8. 使用python调用dll库

    2024-07-20 10:48:01       24 阅读
  9. 数据结构之栈、队列和数组的基本概念

    2024-07-20 10:48:01       23 阅读