文件上传
文件上传
简介
- 文件上传,是指将本地图片、视频、音频等文件上传到服务器,供其他用户浏览或下载的过程。
- 文件上传在项目中应用非常广泛,我们经常发微博、发微信朋友圈都用到了文件上传功能。
本地存储
本地存储缺点:占用服务端的存储空间,并且文件上传后,如果文件没有被使用,那么文件也会被占用,浪费服务器的存储空间。
文件上传的原理
- 本地存储文件上传的原理,就是将客户端上传的文件存储到服务器的硬盘上,然后再响应上传成功信息给客户端。
前端处理注意
- 上传文件必须使用
post请求,并且请求头类型应该为multipart/form-data,否则服务器无法获取到文件。文件的原始类型为二进制文件
后端处理
MultipartFile对象中的静态方法
| 方法名 | 描述 |
|---|---|
bytes[] getBytes() | 获取文件字节数组 |
Sting getOriginalFilename() | 获取原始文件名 |
String getContentType() | 获取文件类型 |
long getSize() | 获取文件大小 单位字节 |
InputStream getInputStream() | 获取接收文件内容的输入流 |
配置文件上传大小限制
#配置单个文件上传大小限制 默认为1M
spring.servlet.multipart.max-file-size=10MB
# 配置单个请求最大大小限制(一次请求中是可以上传多个文件)
spring.servlet.multipart.max-request-size=100MB
package com.springboot.Controller;
import com.springboot.Pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.UUID;
@RestController
@CrossOrigin
@RequestMapping("/upload")
@Slf4j
//文件上传接口
public class UploadController {
/**
* 文件上传
* MultipartFile 文件类型参数
*/
@PostMapping
public Result upload(MultipartFile file) throws IOException {
//使用uuid生成唯一文件名
UUID uuid = UUID.randomUUID();
//获取文件拓展名
//获取。搜所在索引
int indexed = Objects.requireNonNull(file.getOriginalFilename()).indexOf(".");
//截取文件拓展名
String ext = file.getOriginalFilename().substring(indexed);
//拼接文件名
String fileName = uuid + ext;
//将文件保存在当前项目下
File uploadPath = new File("E:\\images\\static\\uploads", fileName);
uploadPath.getParentFile().mkdirs();
file.transferTo(uploadPath);
log.info("文件上传成功 {}", uploadPath.toString());
return Result.success(file.getOriginalFilename());
}
}
阿里云OSS
阿里云存储OSS 是一款海量、安全、低成本、高可靠的云存储服务,使用OSS,你可以通过网络随时存储和调用包括文本。图片。音频和视屏在内的各种文件
- 操作文档
加入依赖
<!-- 阿里云oss依赖-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.17.4</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
编写文件上传工具类(简单文件上传示例)
package com.springboot.Utils;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.springboot.Pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;
@Slf4j
@Component
//上传文件工具类
public class UploadUtils {
//阿里云oss存储根路径
private final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
//填写Bucket名称
private final String bucketName = "web--uploads";
// 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
private final String region = "cn-beijing";
public String uploadFile(MultipartFile file) throws com.aliyuncs.exceptions.ClientException {
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
//使用uuid生成唯一文件名
UUID uuid = UUID.randomUUID();
//获取文件拓展名
//获取。搜所在索引
int indexed = Objects.requireNonNull(file.getOriginalFilename()).indexOf(".");
//截取文件拓展名
String ext = file.getOriginalFilename().substring(indexed);
log.info("文件名{}", file.getOriginalFilename());
//拼接文件名
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = uuid + ext;
log.info("文件名123{}", objectName);
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
// 创建OSSClient实例。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
InputStream inputStream = file.getInputStream();
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
// 创建PutObject请求。
PutObjectResult result = ossClient.putObject(putObjectRequest);
//返回结果
String[] urlArr = endpoint.split("//");
return urlArr[0] + "//" + bucketName + "." + urlArr[1] + "/" + objectName;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
return null;
} catch (ClientException | IOException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
return null;
} finally {
ossClient.shutdown();
}
}
}