1. 条件
1.1 前端要素:
- 表单项 type=”file”
- 提交方式 post
- 表单enctype属性 multipart/form-data
1.2 后端要素:
- MultipartFile
2 本地存储:
不常用。
存储在磁盘中无法在前端页面直接访问
保存文件时可以使用UUID为每一个文件创建一个独一无二的文件名而防止被覆盖。
- String getOriginalFilename (); // 获取原始文件名
- void transferTo (File dest); // 将接收的文件转存到磁盘文件中
- long getSize (); // 获取文件的大小,单位:字节
- byte [] getBytes (); // 获取文件内容的字节数组
- InputStream getInputStream (); // 获取接收到的文件内容的输入流
- 在 Spring Boot 中,文件上传默认单个文件允许最大大小为 1M。
- 如果需要上传大文件,可以进行如下配置:(在
application.properties
或application.yml
中进行设置)- 配置单个文件最大上传大小:
spring.servlet.multipart.max - file - size = 10MB
- 配置单个请求最大上传大小(一次请求可以上传多个文件):
spring.servlet.multipart.max - request - size = 100MB
- 配置单个文件最大上传大小:
例:
前端:upload.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="username"><br>
年龄:<input type="text" name="age"><br>
头像:<input type="file" name="image"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
后端:UploadController.java:
此处保存在了项目内,一般使用绝对路径保存在存储的特定位置中。
特别注意,此处使用到File path = new File(ResourceUtils.getURL(“classpath:”).getPath())得到的是
Spring Boot中是根目录下: target\classes。(开发时使用的是src下的,但是运行时是target下的!!!)
package org.example.ssmpratice1.controller;
import lombok.extern.slf4j.Slf4j;
import org.example.ssmpratice1.pojo.Result;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
public class UploadController {
@PostMapping("/upload")
public Result upload(String username, Integer age, MultipartFile image) throws IOException {
log.info("上传文件:{},{},{}",username,age,image);
//命名文件
String fileName = UUID.randomUUID().toString()+image.getOriginalFilename();
log.info("新的文件名:{}",fileName);
//设置文件保存路径
// 获取项目根目录的文件对象(在Spring Boot中是根目录下: target\classes)!!!!!!!!!!!!!!!!!!!!
File path = new File(ResourceUtils.getURL("classpath:").getPath());
log.info("path:"+path);
// 构建文件保存的完整相对路径
String savePath = path.getAbsolutePath() +"/static/uploadFiles/images/";
//保存文件
image.transferTo(new File(savePath+fileName));
//回写保存后的URL(前端访问以static为根目录)
String url="uploadFiles/images/"+fileName;
log.info("url:"+url);
return Result.success(url);
}
}
3 阿里云OSS
此部分先挖坑,后续实际项目时在填坑