上传文件是我们日常使用最为广泛的功能之一,比如App端上传头像。本章演示如何从客户端上传到 Spring Boot 开发的 Api中。

本项目源码 github 下载

1 新建 Spring Boot Maven 示例工程项目

注意:本示例是用 IDEA 开发工具

  1. File > New > Project,如下图选择 Spring Initializr 然后点击 【Next】下一步
  2. 填写 GroupId(包名)、Artifact(项目名) 即可。点击 下一步

    groupId=com.fishpro

    artifactId=upload
  3. 选择依赖 Spring Web Starter 前面打钩。
  4. 项目名设置为 spring-boot-study-upload.

文件上传不需要引入第三方组件。

2 依赖引入 Pom.xml

为了演示代码,这里引入 thymeleaf

<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-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

3 编写上传示例

本章代码主要演示单文件上传和多文件上传,前端采用 thymeleaf 模板,实际上就是一个html文件。文件清单包括

  1. uploadfile.html 前端文件
  2. FileController.java 控制层文件
  3. FileUtil.java 文件常用类

3.1 控制层代码

主要使用 MultipartFile 来实现,如下代码 /upload 和 /uploads 分别为单文件上传和多文件上传。其中 @Value("${fishpro.uploadPath}") 是配置文件中设置的。

server.port=8086
fishpro.uploadPath=/Users/jiaojunkang/Desktop/upload/
@Controller
public class FileController { @Value("${fishpro.uploadPath}")
private String uploadPath; @GetMapping("/uploadfile")
public String uploadfile(){
return "uploadfile";
} /**
* 单文件
* */
@PostMapping("/upload")
@ResponseBody
Object upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
Map<String,Object> map=new HashMap();
map.put("status",0);
String fileName = file.getOriginalFilename();
fileName = UUID.randomUUID().toString(); //对文件名称重命名 try {
FileUtil.uploadFile(file.getBytes(), uploadPath, fileName);
map.put("filename",fileName);
} catch (Exception e) {
map.put("status",-1);
map.put("message",e.getMessage()); } return map;
} /**
* 多文件
* */
@PostMapping("/uploads")
@ResponseBody
Object uploads(@RequestParam("files") MultipartFile [] files, HttpServletRequest request) {
Map<String,Object> map=new HashMap();
map.put("status",0);
List<String> filenames=new ArrayList<>();
for (MultipartFile file: files
) {
String ext = file.getOriginalFilename().split("\\.")[1];
String fileName = file.getOriginalFilename();
//fileName = UUID.randomUUID().toString()+"."+ext; //对文件名称重命名 try {
FileUtil.uploadFile(file.getBytes(), uploadPath, fileName);
filenames.add(fileName);
} catch (Exception e) {
map.put("status",-1);
map.put("message",e.getMessage());
return map; }
} map.put("filename",filenames);
return map;
}
}

3.2 前端文件

前端文件这里演示的比较简单,可以有多中形态,这里使用 form 来提交。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<hr/>
<div>单位文件</div>
<form enctype="multipart/form-data" method="post" action="/upload">
文件 <input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
<hr/>
<div>多文件</div> <form enctype="multipart/form-data" method="post" action="/uploads">
<p>文件1<input type="file" name="files"/></p>
<p>文件2<input type="file" name="files"/></p>
<p>文件3<input type="file" name="files"/></p>
<p><input type="submit" value="上传"/></p>
</form>
</body>
</html>

3.3 文件保存类

public class FileUtil {

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
} public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
return true;
} else {
return false;
}
} else {
return false;
}
} public static String renameToUUID(String fileName) {
return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
}
}

本项目源码 github 下载

Spring Boot 文件上传简易教程的更多相关文章

  1. spring boot文件上传、下载

    主题:Spring boot 文件上传(多文件上传)[从零开始学Spring Boot]http://www.iteye.com/topic/1143595 Spring MVC实现文件下载http: ...

  2. Spring Boot 文件上传原理

    首先我们要知道什么是Spring Boot,这里简单说一下,Spring Boot可以看作是一个框架中的框架--->集成了各种框架,像security.jpa.data.cloud等等,它无须关 ...

  3. Spring Boot 文件上传

    其实网上已经有很多这样的文章了.为什么我还要记录一下呢?原因是在工作中对接外系统时,碰到了他们调取我们文件上传接口确存在着http请求头部规范的情况,从而导致用传统方法获取不到参数.今天就来整理下Sp ...

  4. spring boot 文件上传大小限制

    错误信息 : Spring Boot:The field file exceeds its maximum permitted size of 1048576 bytes. 解决方法一:在启动类添加如 ...

  5. 从.Net到Java学习第十篇——Spring Boot文件上传和下载

    从.Net到Java学习系列目录 图片上传 Spring Boot中的文件上传就是Spring MVC中的文件上传,将其集成进来了. 在模板目录创建一个新的页面 profile/uploadPage. ...

  6. Spring Boot 文件上传与下载

    原文地址: https://www.cnblogs.com/studyDetail/p/7003253.html 1.在pom.xml文件中添加依赖 <project xmlns="h ...

  7. (29)Spring boot 文件上传(多文件上传)【从零开始学Spring Boot】

    文件上传主要分以下几个步骤: (1)新建maven java project: (2)在pom.xml加入相应依赖: (3)新建一个表单页面(这里使用thymleaf); (4)编写controlle ...

  8. spring boot 文件上传工具类(bug 已修改)

    以前的文件上传都是之前前辈写的,现在自己来写一个,大家可以看看,有什么问题可以在评论中提出来. 写的这个文件上传是在spring boot 2.0中测试的,测试了,可以正常上传,下面贴代码 第一步:引 ...

  9. Spring Boot文件上传

    一.创建一个简单的包含WEB依赖的SpringBoot项目 二.配置文件上传的文件大小限制 # 上传文件总的最大值spring.servlet.multipart.max-request-size=1 ...

随机推荐

  1. AcWing 532. 货币系统

    #include <cstring> #include <iostream> #include <algorithm> using namespace std; ; ...

  2. Oracle VM VirtualBox - ping不通虚拟机

    问题描述 用Oracle VM VirtualBox创建虚拟机后,本机电脑ping不通虚拟机 解决方案 https://www.cnblogs.com/ranrongzhen/p/6958485.ht ...

  3. python3练习100题——006

    继续做题-经过py3测试 原题链接:http://www.runoob.com/python/python-exercise-example6.html 题目:斐波那契数列. 我的代码: def fi ...

  4. 阿里云 Linux 挂在硬盘 翻了几篇这个最好

    原文 :https://www.jianshu.com/p/fa587bbfbb60 阿里云数据盘挂载完整过程 阿里云挂载云盘第一步 在阿里云管理员后台,云盘管理中心挂载好云盘在哪个服务器上面. 登录 ...

  5. Web API幂等、超时优化

    幂等 当涉及业务数据的变更,不是简单的数据查询时, 在调用方相同条件有效重复请求时,就需要保持业务系统数据之间的一致性,不管请求多少次都会返回相同的结果. 比如一个订单支付接口,第一次请求返回支付成功 ...

  6. javaFx中Image的路径问题

    网络图像文件前面加“http://”,而本地文件则要加“file:”.将源代码改为: Image image = new Image("file:image/qq.jpg"); I ...

  7. 每天进步一点点------ORCAD Capture CIS

    ORCAD Capture CIS 一.建工程及设置 1.选主菜单 file->new->project ;弹出 project wizard 对话框,取名Myproject : Mypr ...

  8. win api + ffmpeg 播放 mp3 音乐

    暂时记录,还有很多需要改善的地方一直没弄好,比如不知道怎么对上正确的播放速度. 有一些多余的代码,不用在意. #include <iostream> #include <fstrea ...

  9. poj 3057(bfs+二分匹配)

    题目链接:http://poj.org/problem?id=3057 题目大概意思是有一块区域组成的房间,房间的边缘有门和墙壁,'X'代表墙壁,'D'代表门,房间内部的' . '代表空区域,每个空区 ...

  10. pycharm开发flask指定ip、端口无效

    原因分析 是因为使用了pycharm的版本的问题.并不是flask框架本身的问题(不管你是如何设置的flask配置,通过加载config也好,还是通过run的时候传入形参也好,均不影响) 可以很明显的 ...