SpringBoot文件上传

SpringBoot文件上传

上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个 Spring

Boot 上传文件的小案例。

1、pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.0.RELEASE</version></parent><groupId>com.example</groupId><artifactId>spring-boot-file-upload</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-boot-file-upload</name><description>spring-boot-file-upload</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><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></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

引入了spring-boot-starter-thymeleaf做页面模板引擎,写一些简单的上传示例。

2、启动类设置

package com.example;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);}
}

3、配置文件

#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
#search multipart
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

4、编写前端页面

上传页面upload.html

<!DOCTYPE html>
<html>
<body><h1>Spring Boot file upload example</h1><form method="POST" action="/upload" enctype="multipart/form-data"><input type="file" name="file"/><br/><br/><input type="submit" value="Submit"/>
</form></body>
</html>

非常简单的一个 Post 请求,一个选择框选择文件,一个提交按钮,效果如下。

在这里插入图片描述

上传结果展示页面uploadStatus.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body><h1>Spring Boot - Upload Status</h1><div th:if="${message}"><h2 th:text="${message}"/>
</div></body>
</html>

效果图如下:

在这里插入图片描述

5、编写上传控制类

访问 localhost 自动跳转到上传页面:

package com.example.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;@Controller
public class UploadController {// 上传的文件的保存路径private static String UPLOADED_FOLDER = "D:\\content\\【完】SpringBoot\\【完】007-SpringBoot文件上传\\";@GetMapping("/")public String index() {return "upload";}@PostMapping("/upload")public String singleFileUpload(@RequestParam("file") MultipartFile file,RedirectAttributes redirectAttributes) {if (file.isEmpty()) {redirectAttributes.addFlashAttribute("message", "Please select a file to upload");return "redirect:uploadStatus";}try {// 获取文件并设置保存路径byte[] bytes = file.getBytes();Path dir = Paths.get(UPLOADED_FOLDER);Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());// 不存在的话则创建if (!Files.exists(dir)) {Files.createDirectories(dir);}Files.write(path, bytes);// 该方法可以直接上传到目标文件// file.transferTo(target);redirectAttributes.addFlashAttribute("message","You successfully uploaded '" + file.getOriginalFilename() + "'");} catch (IOException e) {redirectAttributes.addFlashAttribute("message", "Server throw IOException");e.printStackTrace();}return "redirect:/uploadStatus";}@GetMapping("/uploadStatus")public String uploadStatus() {return "uploadStatus";}}

在这里插入图片描述

上面代码的意思就是,通过MultipartFile读取文件信息,如果文件为空跳转到结果页并给出提示;如果不为空

读取文件流并写入到指定目录,最后将结果展示到页面。

MultipartFile是Spring上传文件的封装类,包含了文件的二进制流和文件属性等信息,在配置文件中也可对相

关属性进行配置,基本的配置信息如下:

  • spring.http.multipart.enabled=true #默认支持文件上传.

  • spring.http.multipart.file-size-threshold=0 #支持文件写入磁盘.

  • spring.http.multipart.location= # 上传文件的临时目录

  • spring.http.multipart.max-file-size=1Mb # 最大支持文件大小

  • spring.http.multipart.max-request-size=10Mb # 最大支持请求大小

最常用的是最后两个配置内容,限制文件上传大小,上传时超过大小会抛出异常。

更多配置信息参考这里:

https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties

6、异常处理

package com.example.controller;import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;/*** 全局异常处理*/
@ControllerAdvice
public class GlobalExceptionHandler {//https://jira.spring.io/browse/SPR-14651//4.3.5 supports RedirectAttributes redirectAttributes@ExceptionHandler(MultipartException.class)public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());return "redirect:/uploadStatus";}
}

设置一个@ControllerAdvice用来监控Multipart上传的文件大小是否受限,当出现此异常时在前端页面给出提

示。利用@ControllerAdvice可以做很多东西,比如全局的统一异常处理等。

这样一个使用 Spring Boot 上传文件的简单 Demo 就完成了。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/133802.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【NI-DAQmx入门】NI-DAQmx之MATLAB/SIMULINK支持

Data Acquisition Toolbox™ 提供用于配置数据采集硬件、将数据读入 MATLAB 和 Simulink 以及将数据写入 DAQ 模拟和数字输出通道的应用程序和函数。该工具箱支持多种 DAQ 硬件&#xff0c;包括来自 National Instruments™ 和其他供应商的 USB、PCI、PCI Express 、PXI 和 PXI…

torch.cuda.is_available()=false的原因

1、检查是否为nvidia显卡&#xff1b; 2、检查GPU是否支持cuda; 3、命令行cmd输入nvidia-smi&#xff08;中间没有空格&#xff09;&#xff0c;查看显卡信息&#xff0c;cuda9.2版本只支持Driver Version>396.26&#xff1b;如果小于这个值&#xff0c;那么你就需要更新显…

详解--Hash(中文也称散列、哈希)

参考链接 参考链接2 1. hash 概念 1.1 什么是 hash Hash 也称散列、哈希&#xff0c;对应的英文都是 Hash。 基本原理就是把任意长度的输入&#xff0c;通过 Hash 算法变成固定长度的输出。这个映射的规则就是对应的 Hash 算法&#xff0c;而原始数据映射后的二进制串就是哈希…

不用流氓软件,如何在户外使用手机听下载到家中电脑里的音乐文件呢?

文章目录 本教程解决的问题是&#xff1a;按照本教程方法操作后&#xff0c;达到的效果是本教程使用环境&#xff1a;1 群晖系统安装audiostation套件2 下载移动端app 很多老铁想在上班路上听点喜欢的歌或者相声解解闷儿&#xff0c;于是打开手机上的某雅软件和某音乐软件点进去…

微信图片变小kb电脑怎么改?手机图片压缩的方法

平时在使用微信发送图片的时候&#xff0c;如果图片太大超出了平台限制是无法顺利发送的&#xff0c;很多小伙伴都不知道怎么处理这样的情况&#xff0c;其实可以直接使用压缩图的图片压缩来处理&#xff0c;打开浏览器就能直接完成微信图片压缩&#xff0c;在图片压缩大小时&a…

华为政企园区网络交换机产品集

产品类型产品型号产品说明 核心/汇聚交换机CloudEngine S5731-H24P4XCCloudEngine S5731-H24P4XC 提供 24个10/100/1000BASE-T以太网端口&#xff0c;4个万兆SFP&#xff0c;CloudEngine S5731-H 系列交换机是华为公司推出的新一代智能千兆交换机&#xff0c;基于华为公司统…

x264交叉编译(ubuntu+arm)

1.下载源码 https://code.videolan.org/videolan/x264 在windows下解压&#xff1b;复制到ubuntu&#xff1b; 2.进入源码文件夹-新建脚本文件 touch sp_run.sh 3.在sp_run.sh文件中输入 #!/bin/sh./configure --prefix/home/alientek/sp_test/x264/sp_install --enable-…

大数据管理平台有什么用?如何利用大数据管理平台优化企业运营?

在数字化时代&#xff0c;大数据管理平台已经成为了企业和组织不可或缺的工具。它不仅可以帮助企业跟踪和解决报修问题&#xff0c;还为数据分析提供了丰富的信息。通过合理利用大数据管理平台进行数据分析&#xff0c;企业可以更好地了解其运营情况&#xff0c;优化设备维修和…

python selenium 点击表格中的一系列按钮并输出弹窗内容到csv

一个python selenium的实用实例&#xff0c;比demo重&#xff0c;但也不算太复杂。 trick总结如下&#xff1a; 最新chromedriver的地址&#xff0c;https://googlechromelabs.github.io/chrome-for-testing&#xff0c;这很重要&#xff0c;不然就要处理chrome自动更新之类的…

【数据结构】败者树的建树与比较过程

文章目录 前置知识归并段 建树过程比较过程疑问为什么比较次数减少了&#xff1f;如果某个归并段的元素一直获胜&#xff0c;没有元素了怎么办&#xff1f;处理方法 1处理方法 2 前置知识 归并段 外部排序算法通常用于处理大规模数据&#xff0c;其中数据量远超过计算机内存的…

擎创动态 | 开箱即用!擎创科技联合中科可控推出大模型一体机

一、金融行业大模型一体机发布 10月26日至27日&#xff0c;2023金融科技安全与创新大会顺利召开。会上&#xff0c;中科可控联合擎创科技、卓世科技、文因互联、百川智能、捷通华声、智谱华章、易道博识等9大厂商&#xff0c;发布了9款金融行业大模型一体机&#xff0c;为金融…

云贝教育 |【PGCA题目解析-1】psql元命令\du和\dg都可以列出角色或用户,请问这两个命令是否等价?

考试科目&#xff1a;PGCA-E-090 考试题量&#xff1a;40 道单项选择题、10 道多项选择题&#xff08;每题 2 分&#xff09; 通过分数&#xff1a;60% 考试时间&#xff1a;60min 本文为云贝教育刘峰&#xff08;微信&#xff1a;yunbee_DBA&#xff09;原创&#xff0c;请…

Netty入门指南之NIO Channel详解

作者简介&#xff1a;☕️大家好&#xff0c;我是Aomsir&#xff0c;一个爱折腾的开发者&#xff01; 个人主页&#xff1a;Aomsir_Spring5应用专栏,Netty应用专栏,RPC应用专栏-CSDN博客 当前专栏&#xff1a;Netty应用专栏_Aomsir的博客-CSDN博客 文章目录 参考文献前言Channe…

‘vite‘ is not recognized as an internal or external command

标题翻译后就是&#xff1a;‘vite‘ 不是内部或外部命令&#xff0c;也不是可运行的程序 或批处理文 运行一个由 Vite 构建的 Vue3 项目&#xff0c;之前还好好的能正常跑&#xff0c; 但拉取新代码之后再次执行 npm run dev 就提示 ‘vite’ 不是内部或外部命令&#xff0…

vue 实现在线预览Excel-LuckyExcel/LuckySheet实现方案

一、准备工作 1. npm安装 luckyexcel npm i -D luckyexcel 2.引入luckysheet 注意&#xff1a;引入luckysheet&#xff0c;只能通过CDN或者直接引入静态资源的形式&#xff0c;不能npm install。 个人建议直接下载资源引入。我给你们提供一个下载资源的地址&#xff1a; …

11月7日,每日信息差

今天是2023年11月07日&#xff0c;以下是为您准备的17条信息差 第一、五粮液否认内部讨论提价传闻 第二、雷军证实小米14销量已超百万台 第三、支付宝生活号全面开放UGC入口。据了解&#xff0c;今年以来&#xff0c;支付宝生活号陆续上线了创作者中心、热点榜单等多个内容产…

【NeurIPS 2020】基于蒙特卡罗树搜索的黑箱优化学习搜索空间划分

Learning Search Space Partition for Black-box Optimization using Monte Carlo Tree Search 目标&#xff1a;从采样&#xff08;Dt ∩ ΩA&#xff09;中学习一个边界&#xff0c;从而最大化两方的差异 先使用Kmeans在特征向量上&#xff08; [x, f(x)] &#xff09;聚类…

20231107-前端学习炫酷菜单效果和折叠侧边栏

炫酷菜单效果 代码 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>炫酷菜单效果</title><…

第一个ARM程序裸板点灯

硬件知识LED原理图 如何点亮一个LED灯&#xff1f; 看原理图&#xff0c;确定控制LED的引脚。看主芯片的芯片手册&#xff0c;确定如何设置控制这个引脚。写程序。 LED有插脚封装的、贴片封装的。 它们长得完全不一样&#xff0c;因此我们在原理图中把它们抽象出来。 点亮…

Flutter 自签名证书

前言 Flutter项目中服务器使用了自签名证书&#xff0c;如果直接使用https请求或者wss请求的话会报证书签名错误。 HandshakeException: Handshake error in client (OS Error: I/flutter (28959): │ &#x1f4a1; CERTIFICATE_VERIFY_FAILED: unable to get local issuer c…