SpringBoot文件上传下载和多文件上传(图文详解)

从零搭建开发脚手架 Spring Boot文件上传的多种方式、原理及遇到的问题 手绘了下图所示的kafka知识大纲流程图(xmind文件不能上传,导出图片展现),但都可提供源文件给每位爱学习的朋友[外链图片转存中…(img-0LHyWaMX-1711818489777)][外链图片转存中…(img-LltDAEFM-1711818489777)][外链图片转存中…(img-bn8bdkap-1711818489778)][外链图片转存中…(img-UqsFOwAh-1711818489778)] 阅读详情

本人微信公众号:CPP进阶之旅
如果觉得这篇文章对您有帮助,欢迎关注 “CPP进阶之旅” 学习更多技术干货

最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的java代码:
1、开发环境:
IDEA15+ Maven+JDK1.8
2、新建一个maven工程:
这里写图片描述
3、工程框架
这里写图片描述
4、pom.xml文件依赖项

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>SpringWebContent</groupId>
  <artifactId>SpringWebContent</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SpringWebContent Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.3.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <build>
    <finalName>SpringWebContent</finalName>
  <plugins>
  <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
  </plugin>
</plugins>
  </build>
</project>

5、Application.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

6、FileController.java

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
public class FileController {
    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    //文件上传相关代码
    @RequestMapping(value = "upload")
    @ResponseBody
    public String upload(@RequestParam("test") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为:" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的后缀名为:" + suffixName);
        // 文件上传后的路径
        String filePath = "E://test//";
        // 解决中文问题,liunx下中文路径,图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    //文件下载相关代码
    @RequestMapping("/download")
    public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){
        String fileName = "FileUploadTests.java";
        if (fileName != null) {
            //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
            String realPath = request.getServletContext().getRealPath(
                    "//WEB-INF//");
            File file = new File(realPath, fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" +  fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }
    //多文件上传
    @RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
    @ResponseBody
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();

                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => "
                            + e.getMessage();
                }
            } else {
                return "You failed to upload " + i
                        + " because the file was empty.";
            }
        }
        return "upload successful";
    }

7、index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<form action="/upload" method="POST" enctype="multipart/form-data">
    文件:<input type="file" name="test"/>
    <input type="submit" />
</form>
<a href="/download">下载test</a>
<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data" action="/batch/upload">
    <p>文件1:<input type="file" name="file" /></p>
    <p>文件2:<input type="file" name="file" /></p>
    <p><input type="submit" value="上传" /></p>
</form>
</html>

本文代码参考Spring官网:https://spring.io/guides/gs/serving-web-content/
完整工程地址:http://download.youkuaiyun.com/detail/coding13/9739116

欢迎关注我的个人微信公众号,查看专业的客户端/服务端开发知识、笔试面试题目、程序员职场经验与心得分享。
在这里插入图片描述

SpringBoot图文教程4—SpringBoot 实现文件上传下载 有天上飞的概念,就要有落地的实现 概念+代码实现是本文的特点,教程将涵盖完整的图文教程,代码案例 文章结尾配套自测面试题,学完技术自我测试更扎实 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 大哥大姐新年好,点赞转发不要少 SpringBoot 图文系列教程技术大纲 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1「概念+案例 思维导图」「... 阅读详情

相关推荐

Spring Boot实现多文件上传

在生成项目时,选择适当的依赖项,如Web和Thymeleaf,以便支持文件上传和页面展示。通过创建Spring Boot项目、编写文件上传页面、实现文件上传的控制器以及配置文件上传的限制,我们可以轻松地实现多文件上传功能。选择要上传的文件并点击上传按钮,文件将被上传到服务器上的指定目录。接下来,我们需要创建一个文件上传的页面。接下来,我们需要创建一个控制器来处理文件上传的请求,并将文件保存到服务器上的指定目录。在上述示例中,我们创建了一个包含文件选择和上传按钮的表单。属性设置同时上传的文件数量的限制。

CodeShiftZ的博客 947

SpringBoot文件上传

SpringMVC对文件上传做了简化,在SpringBoot中对此做了更进一步的简化,文件上传更为方便。根据这里的配置可以看出,如果开发者没有提供MultipartResolver,那么默认采用的MultipartResolver就是StandardServletMultipartResolver。因此,在SpringBoot中上传文件甚至可以做到零配置。下面来看具体上传过程。...

m0_59092234的博客 2万+

Spring Boot进阶(24):秒传!快速实现高效多文件上传的最佳解决方案

springboot项目如何快速实现多文件上传?若不会,我便手把手教你,超级详细,就等你来白嫖。

**My Coding Family** 8658

总结SpringBoot文件上传的几种方式

应用开发过程中,文件上传是一个基础的扩展功能,本文梳理一下在SpringBoot当中文件上传所涉及的技术及实现,内容主要包括两部分,上传到服务器本地,以前的文章已经写得比较详细了,包括了单文件、多文件的上传,可以跳转至了解,另一部分是使用对象存储服务(比如阿里OSSMinIO等)来存储上传的文件,也是比较主流的一种方式,本站就是使用了腾讯云的对象存储服务搭建的静态网站,还有现在完成的一个外卖平台项目,其中菜品的图片资源就存储在阿里OSS。

weixin_46302607的博客 4949

中标麒麟,postgres报错invalid value for parameter "timeZone":"Asia/Beijing"

在中标麒麟服务器上,安装postgres,启动tomcat容器时,报invalid value for parameter "timeZone":"Asia/Beijing"。 查看postgres运行日志,也报同样的错误。 报错原因:服务器的时区,在Postgres支持的时区目录中找不到。当时在服务器上信息为Beijing 解决步骤: 1. cat /etc/sysconfig/cloc

u010213931的博客 7924

CentOS Stream 9中安装MySQL的详细步骤

本文详细介绍了在CentOS Stream 9系统中如何进行MySQL的在线安装、离线安装以及忘记密码的恢复操作。通过阅读本文,您将能够了解并掌握在CentOS Stream 9上安装MySQL的步骤,以及在遇到忘记密码的情况下的解决方案。

小白典的博客 7258

java多文件下载Springboot,详解SpringBoot文件上传下载和多文件上传(图文)

最近在学习springboot,以下是最近学习整理的实现文件上传下载的java代码:1、开发环境:idea15+ maven+jdk1.82、新建一个maven工程:3、工程框架4、pom.xml文件依赖项xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&g...

weixin_35848310的博客 284

携程酒店数据爬取进阶:动态接口破解与反反爬策略实战

本文详细解析了携程酒店数据爬取的进阶技巧,包括动态接口参数破解、反爬虫策略对抗及企业级采集方案实现。重点介绍了eleven参数的生成逻辑、动态Cookie维护方法,以及如何应对携程的请求指纹检测和行为模式识别。通过实战案例,帮助开发者高效获取酒店价格数据,同时遵守行业规范。

eee77的博客 1078

springboot 上传文件解析入库_SpringBoot文件上传下载和多文件上传(图文详解)

最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码:1、开发环境:IDEA15+ Maven+JDK1.82、新建一个maven工程: 3、工程框架 4、pom.xml文件依赖项xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"...

weixin_31837543的博客 394

生信分析服务MR孟德尔随机化单细胞测序转录组数据分析网络药理学

通过上述技术整合,可实现从基因-环境-疾病关联到药物机制解析的全链条研究,为疾病机制解析和药物研发提供新思路。结合,是当前生物信息学领域的前沿方法,尤其在疾病机制解析、靶点发现和药物研发中展现出巨大潜力。

matlabgoodboy的博客 1520

Red Hat Enterprise Linux 9.2

安装Red Hat Enterprise Linux 9.2

zhurobert的博客 942

springboot 实现单文件上传/多文件上传/文件下载

java 开发经常需要用到文件上传,接下来博主就创建一个springboot项目,实现单文件上传/多文件上传/文件下载功能 1.先看一下博主的项目结构图 2.application.yml主要配置 3.如上图创建项目 创建FileUpload类: package com.study.controller; import lombok.extern.slf4j.Slf4j; i...

Dream_xun的专栏 789

麒麟 ARMv10 SP3 安装 Oracle 19c 官方文档 或 教程

在麒麟ARMv10 SP3系统上安装Oracle 19c需要特别注意架构兼容性。

qq_43032338的博客 2941

gitee最多上传多大文件_SpringBoot图文教程4—SpringBoot 实现文件上传下载

有天上飞的概念,就要有落地的实现概念+代码实现是本文的特点,教程将涵盖完整的图文教程,代码案例文章结尾配套自测面试题,学完技术自我测试更扎实 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 大哥大姐新年好,点赞转发不要少SpringBoot 图文系列教程技术大纲SpringBoot 图文教程系列文章目录SpringBoot图文教程1「概念+案例 思维导图」「基础篇上」Spring...

weixin_39653764的博客 251

Source Insight 4.0舒适黑主题 仿心情看的舒服就行

Source Insight 4.0主题 仿心情看的舒服就行 source insight自带的主题怎么看怎么别扭,于是在试用全网各种主题配色后,在其中一个基础上自定义了c/c++的语法配色 截全图有点糊 函数定义 全局变量 局部变量 枚举变量引用 全局变量引用及结构体成员 宏定义引用 ----------------------后面会再把主题文件贴上来-------------- ...

weixin_43443402的博客 1303

【二】MADDPG多智能体算法实现(parl)【追逐游戏复现】

论文全称:Multi-Agent Actor-Critic for Mixed Cooperative-Competitive Environments 论文原文:https://download.youkuaiyun.com/download/sinat_39620217/16203960 论文翻译:https://blog.youkuaiyun.com/qiusuoxiaozi/article/details/79066612 ...

丨汀、的博客 2万+

java上传视频到七牛云_SpringBoot图文教程4—SpringBoot 实现文件上传下载

有天上飞的概念,就要有落地的实现概念+代码实现是本文的特点,教程将涵盖完整的图文教程,代码案例文章结尾配套自测面试题,学完技术自我测试更扎实 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 大哥大姐新年好,点赞转发不要少SpringBoot 图文系列教程技术大纲SpringBoot 图文教程系列文章目录SpringBoot图文教程1「概念+案例 思维导图」「基础篇上」Spring...

weixin_33859693的博客 416

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

SpringBoot图文教程4—SpringBoot 实现文件上传下载(亲测)

SpringBoot 图文教程系列文章目录 SpringBoot图文教程1「概念+案例 思维导图」「基础篇上」 SpringBoot图文教程2—日志的使用「logback」「log4j」 SpringBoot图文教程3—「‘初恋’情结」集成Jsp 前言 通过前面三篇的教程,小伙伴们已经可以实现一个web项目了,但是现在项目的功能还有点简单,接下来的文章中将会逐步完善添加新的功能。 本文所有的内容,将会在之前的demo上进行操作。 如果没有写好的demo,请去Git仓库下载

gb4215287的博客 159

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

spring boot文件上传、下载

主题:Spring boot 文件上传(多文件上传)【从零开始学Spring Boot】 http://www.iteye.com/topic/1143595 Spring MVC实现文件下载 http://www.cnblogs.com/jxldjsn/p/5671578.html spring boot 上传文件 http://www.garlic5.com/ziliao.p

zhao1949的专栏 3426

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

上一篇: 使用Httpie调试ElasticSearch环境搭建及简单测试(图文详解)
下一篇: Java Object List Map 转Json学习
Coding13
博客等级 码龄10年 53粉丝 43原创
评论 15
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coding13

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值