首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >springboot 文件的上传下载

springboot 文件的上传下载

作者头像
smallmayi
发布于 2022-05-12 03:21:51
发布于 2022-05-12 03:21:51
76500
代码可运行
举报
文章被收录于专栏:small专栏small专栏
运行总次数:0
代码可运行

SpringMVC的文件上传是通过MultipartResolver(Multipart解析器)处理,MultipartResolver只是一个接口,有两个实现类。 1.CommonsMultipartResolver :依赖Apache FileUpload项目解析Multipart,可以在Spring的各个版本使用,需要依赖第三方jar包。 2.StandardServletMultipartResolver: 是Spring3.1之后的产物,依赖于Servlet3.0或更高版本的实现,不需要第三方jar包。

Springboot实现文件上传

Springboot默认可以使用文件上传,使用transferTo方法保存文件。

示例:FileCtrl.java

服务器根目录创建文件夹放置文件

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@RestController
@Slf4j
public class FileCtrl {

    @PostMapping("/singleFile")
    @ResponseBody
    public String singleFile(@RequestParam("file") MultipartFile file) {
        //判断非空
        if (file.isEmpty()) {
            return "上传的文件不能为空";
        }
        try {
            // 测试MultipartFile接口的各个方法
            log.info("[文件类型ContentType] - [{}]", file.getContentType());
            log.info("[文件组件名称Name] - [{}]", file.getName());
            log.info("[文件原名称OriginalFileName] - [{}]", file.getOriginalFilename());
            log.info("[文件大小] - [{}]", file.getSize());
            //文件路径
            String path = System.getProperty("user.dir") + "/upload/";
            log.info(this.getClass().getName() + "图片路径:" + path);
            File f = new File(path);
            //如果不存在该路径就创建
            if (!f.exists()) {
                f.mkdir();
            }
            File dir = new File(path + file.getOriginalFilename());
            // 文件写入
            file.transferTo(dir);
            return "上传单个文件成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "上传单个文件失败";
        }
    }

    @PostMapping("/multipleFiles")
    @ResponseBody
    public String multipleFiles(@RequestParam("file") MultipartFile[] files) {
        if (null == files && files.length == 0) {
            return null;
        }
        String filePath = System.getProperty("user.dir") + "/uploads/";
        log.info(this.getClass().getName() + "图片路径:" + filePath);
        File f = new File(filePath);
        //如果不存在该路径就创建
        if (!f.exists()) {
            f.mkdir();
        }
        for (MultipartFile mf : files) {
            //文件名称
            String filename = mf.getOriginalFilename();
            if (mf.isEmpty()) {
                return "文件名称:" + filename + "上传失败,原因是文件为空!";
            }
            File dir = new File(filePath + filename);
            try {
                //写入文件
                mf.transferTo(dir);
                log.info("文件名称:" + filename + "上传成功");
            } catch (IOException e) {
                log.error(e.toString(), e);
                return "文件名称:" + filename + "上传失败";
            }
        }
        return "多文件上传成功";
    }
}
html测试

singleFile.html

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>单文件上传</p>
<form method="POST" enctype="multipart/form-data" action="http://localhost:8080/singleFile" >
    文件:<input type="file" name="file"/>
    <input type="submit"/>
</form>
<hr/>
</body>
</html>

multipleFiles.html

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data" action="http://localhost:8080/multipleFiles">
    <p>文件1<input type="file" name="file"/></p>
    <p>文件2<input type="file" name="file"/></p>
    <p><input type="submit" value="上传"/></p>
</form>
</body>
</html>
配置文件application.properties

默认每个文件的配置最大为1Mb,单次请求的文件的总数不能大于10Mb。 修改默认配置大小

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#springboot 2.x
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB

如图,根据提示可知除设置文件大小外还有四个属性可设置如下

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#是否支持 multipart 上传文件,默认true,false无法上传
spring.servlet.multipart.enabled=true
#文件大小阈值,大于这个值将写入磁盘,否则在内存中,默认0,一般不修改
spring.servlet.multipart.file-size-threshold=0
#临时文件目录
spring.servlet.multipart.location=
# 判断是否要延迟解析文件,懒加载,一般不修改
spring.servlet.multipart.resolve-lazily=false
Springboot实现文件下载
单文件下载

传入文件名,下载服务器upload目录下文件

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 @GetMapping(value = "/downSingleFile")
    public String download(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
//        String filePathName = "11你好.docx";
        String filePathName = fileName;
        File file = new File("upload/" + filePathName);
        if (!file.exists()) {
            return "文件不存在";
        }
        //使用URLEncoder解决中文变__问题
        //response.setHeader("Content-Disposition", "attachment;fileName=" + filePathName);
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filePathName, "utf-8"));
        try {
            InputStream inStream = new FileInputStream(file);
            OutputStream os = response.getOutputStream();
            byte[] buff = new byte[1024];
             int i = 0;
            //read方法返回读取到字节数,=0说明到达文件结尾,=-1说明发生错误
            while ((i = inStream.read(buff)) != -1) {
                //write()方法3个参数,可自定义读取字节数0-i;
                os.write(buff, 0, i);
            }
            os.flush();
            os.close();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "下载成功";
    }
多文件下载

多个文件打包下载 解决方法:将需要文件复制到临时文件夹,打包zip下载,删除临时文件夹

找的一个工具类,可直接使用 ZipUtils.java

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
package com.example.demo;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * file-upload
 * 2019/11/19 16:45
 *
 * @author
 * @description 多文件压缩zip
 **/
@Slf4j
public class ZipUtils {

    private static final int BUFFER_SIZE = 2 * 1024;

    /**
     * 压缩成ZIP 方法1
     *
     * @param srcDir           压缩文件夹路径
     * @param out              压缩文件输出流
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         <p>
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */

    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {

        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
            long end = System.currentTimeMillis();
            log.info("压缩完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 压缩成ZIP 方法2
     *
     * @param srcFiles 需要压缩的文件列表
     * @param out      压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param KeepDirStructure 是否保留原来的目录结构, true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */

    private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
            throws Exception {

        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }
                }
            }
        }
    }


    /**
     * 拷贝文件夹
     *
     * @param oldPath
     * @param newPath
     */
    public static void copyDir(String oldPath, String newPath) throws IOException {
        File file = new File(oldPath);
        //文件名称列表
        String[] filePath = file.list();

        if (!(new File(newPath)).exists()) {
            (new File(newPath)).mkdir();
        }

        for (int i = 0; i < filePath.length; i++) {
            if ((new File(oldPath + File.separator + filePath[i])).isDirectory()) {
                copyDir(oldPath + File.separator + filePath[i], newPath + File.separator + filePath[i]);
            }

            if (new File(oldPath + File.separator + filePath[i]).isFile()) {
                copyFile(oldPath + File.separator + filePath[i], newPath + File.separator + filePath[i]);
            }

        }
    }

    /**
     * 拷贝文件
     *
     * @param oldPath
     * @param newPath
     */
    public static void copyFile(String oldPath, String newPath) throws IOException {
        File oldFile = new File(oldPath);
        File file = new File(newPath);
        FileInputStream in = new FileInputStream(oldFile);
        FileOutputStream out = new FileOutputStream(file);
        ;
        //2M
        byte[] buffer = new byte[2097152];

        while ((in.read(buffer)) != -1) {
            out.write(buffer);
        }
        in.close();
        out.close();
    }

}

ctrl层调用工具类下载

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 @GetMapping("/downMultipleFiles")
    public String multipleFiles(HttpServletResponse response, String[] fileName) throws IOException {
        //1.创建临时文件夹
        String downPath = System.getProperty("user.dir") + "/downzip/";
        File f = new File(downPath);
        //如果不存在该路径就创建
        if (!f.exists()) {
            f.mkdir();
        }
        //2.将需要下载文件复制到临时文件夹
//        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < fileName.length; i++) {
            String uploadPath = System.getProperty("user.dir") + "/upload/" + fileName[i];
//            File file = new File(uploadPath);
//            fileList.add(file);
            ZipUtils.copyFile(uploadPath, downPath + "/" + fileName[i]);
        }
        //3.设置response,设置压缩包名称
        response.setContentType("application/zip");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        String filename = format + "down.zip";
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        //4.调用工具类,下载zip
        ZipUtils.toZip(downPath, response.getOutputStream(), true);
//        ZipUtils.toZip(fileList,response.getOutputStream());
        //5.删除临时文件夹
        File[] listFiles = f.listFiles();
        for (int i = 0; i < listFiles.length; i++) {
            listFiles[i].delete();
            log.info("正在删除第" + i + "个文件");
        }
        f.delete();
        return "多文件下载成功";
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-11-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
下载谷歌离线地图瓦片图「建议收藏」
项目中遇到一个需求,需要将某个地图区域的离线地图下载下来,整理很多网上的资料自己实现根据起始点的经纬度下载离线地图,代码如下
全栈程序员站长
2022/11/08
2.9K1
(强烈推荐)基于SSM和BootStrap的共享云盘系统设计(项目实现:文件下载)
在index.js文件中添加downloadFileSelect()和downloadFile()两种方式下载文件,当触发事件时,调用download()方法,向后台请求下载数据,代码如下所示;
天道Vax的时间宝藏
2021/08/11
7130
Java常用工具类2 - 崔笑颜的博客
方法一:简单粗暴,直接使用copy(),如果目标存在,先使用delete()删除,再复制;
崔笑颜
2021/02/02
5100
Java批量下载
查询出需要下载附件的集合,下载附件到临时目录,压缩下载到临时文件夹的附件,生成压缩包,最后下载压缩包
学以致用丶
2022/06/28
7400
Java-工具类之ZIP压缩解压
代码已托管到 https://github.com/yangshangwei/commonUtils
小小工匠
2021/08/17
2.2K0
Android笔记:底部导航栏的动态替换方案
选择IntentService的原因是因为下面的这几个操作都是耗时操作,所以我们干脆都封装到这service里面,我们只需要在合适的时机去启动这个Service就ok了
程思扬
2022/01/10
2.2K0
springboot (八) 文件上传下载
springboot项目中实现简单的上传和下载。 新建springboot项目,前台页面使用的thymeleaf模板,其余的没有特别的配置,pom代码如下: <?xml version="1.0" e
IT架构圈
2018/06/01
1.3K0
Service层代码中FileService.java展示
Service层代码中FileService.java展示 import com.demo.fileTree.configuration.GlobalConfig; import com.demo.fileTree.model.FileHandleResponse; import com.demo.fileTree.model.JstreeNode; import com.demo.fileTree.utils.ZipUtils; import org.springframework.beans.facto
用户1503405
2021/10/07
4200
SpringBoot Feign文件上传
写在前面 Feign 文件上传,与普通的Feign远程调用会有所不同,使用的时候需要注意。 客户端 <feign-form.version>3.0.3</feign-form.version> <!-- 文件上传 --> <dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>${feign-form.version}</version>
诺浅
2020/08/19
1.6K0
SpringBoot文件上传下载
项目中经常会有上传和下载的需求,这篇文章简述一下springboot项目中实现简单的上传和下载。 新建springboot项目,前台页面使用的thymeleaf模板,其余的没有特别的配置,pom代码如
dalaoyang
2018/04/28
1.1K0
通过Java代码自动发布Geoserver的地图服务WMS
GeoServer 顾名思义。是一个Server,它是开源的,允许用户查看和编辑地理数据的服务器,它可以比较容易的在用户之间迅速共享空间地理信息。利用Geoserver可以把数据作为maps/images来发布(利用WMS来实现)也可以直接发布实际的数据(利用WFS来实现),它同时也提供了修改,删除和新增的功能(利用WFS-T)。
我叫刘半仙
2019/03/12
4.4K2
通过Java代码自动发布Geoserver的地图服务WMS
工具类ZipUtils.java代码
工具类ZipUtils.java代码如下: import com.demo.fileTree.model.FileHandleResponse; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.*; im
用户1503405
2021/10/07
8550
【Auto.js】[zip压缩] 将文件夹压缩成zip包
将一个文件夹压缩成一个zip包,可应用于项目文件夹打包成zip, 文件夹过滤了目录中的空文件夹,因此,空文件夹不会被打包到zip包中. 由于本人JS知识有限,JAVA也不懂, 导致该函数, 打包大型文件时, 非常慢,性能低下. 如果@admin 有好的方法, 可以发一下, 谢谢.
红目香薰
2022/11/29
2.1K0
项目知识盲区五
Java IO操作——掌握压缩流的使用(ZipOutputStream、ZipFile、ZipInputStream)[java.util包中]
大忽悠爱学习
2021/12/27
4810
项目知识盲区五
使用java API进行zip递归压缩文件夹以及解压
在本篇文章中,给大家介绍一下如何将文件进行zip压缩以及如何对zip包解压。所有这些都是使用Java提供的核心库java.util.zip来实现的。
字母哥博客
2020/09/23
6K0
struts2上传工具类
package com.midai.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java
用户7108768
2021/09/23
7120
JavaWeb 之文件的上传下载
又到了每周更新博客的时候了,每看到自己发布的随笔阅读量上涨的时候就特别开心,我也会尽自己的努力提高自己的水平,总结出通俗易读的学习笔记,还望大家能多多支持!!! -------------------------------------------------------------------------------------------------------------- 文件的上传 - 设置表单请求方式为 post - 设置表单类型为 file - 设置编码方式  enctype=”multipa
bgZyy
2018/05/16
1.9K0
项目实战工具类(二):ZipUtils(压缩/解压缩文件相关)
import android.content.Context; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; im
听着music睡
2018/12/14
2.3K0
笔记101 | 文件的压缩与解压笔记
由于考虑到文件数量,所以使用的是AddFileTask异步读取 此逻辑并没有把zip文件解压出来,而是以读文件的形式去获取内容,保存到mLogo 打印如下
项勇
2020/07/24
4540
笔记101 | 文件的压缩与解压笔记
【java基础】zip压缩文件
1、代码片段 public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) { boolean flag = false; File sourceFile = new File(sourceFilePath); FileInputStream fis = null; BufferedInputStream bis = null; FileOutputStream
用户5640963
2019/07/25
1.8K0
相关推荐
下载谷歌离线地图瓦片图「建议收藏」
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验