本文共 2611 字,大约阅读时间需要 8 分钟。
在传统的实现中,有两种主要方式可以将图片上传到OSS(Object Storage Service):
前端请求 -> 后端服务器 -> OSS
优点:安全性较高,OSS账号信息不会被用户看到。缺点:可能给后端服务器带来较大的负载压力。直接写在前端JS代码中
优点:效率高,减少了对后端服务器的依赖。缺点:存在安全隐患,用户可以直接看到OSS账号密码信息。因此,最好的方式就是采用服务端签名直传:
这样既不会给服务器带来上传文件的压力,也确保了OSS账号密码信息的安全性。
在Spring Boot项目中,我们需要先配置MinIO客户端。以下是配置文件的内容:
minio.access-key=rootminio.secret-key=rootrootminio.endpoint=http://100.105.180.32:9001minio.bucket=dir1
在Spring配置类中,定义MinIO客户端:
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import io.minio.MinioClient;import org.springframework.beans.factory.annotation.Value;@Configurationpublic class MinioConfig { @Value("${minio.access-key}") private String accessKey; @Value("${minio.secret-key}") private String secretKey; @Value("${minio.endpoint}") private String endpoint; @Bean public MinioClient minioClient() { return MinioClient.builder() .endpoint(endpoint) .credentials(accessKey, secretKey) .build(); }}
在API控制器中,实现签名生成和文件上传:
import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/third/minio")public class MinioApi { private final MinioClient minioClient; @Value("${minio.endpoint}") private String endpoint; @Value("${minio.bucket}") private String bucket; public MinioApi(MinioClient minioClient) { this.minioClient = minioClient; } @RequestMapping(value = "/policy", method = RequestMethod.GET) public Mappolicy() { String objectNamePrefix = "uploads/"; var expiration = ZonedDateTime.now().plusHours(1); var postPolicy = minioClient.getPresignedPostFormData( new PostPolicy( bucket, expiration ).run { addStartsWithCondition("key", objectNamePrefix) addContentLengthRangeCondition(1, 10485760) } ); postPolicy.result.apply { this["url"] = "$endpoint/$bucket" } return postPolicy.result; }}
在前端,实现文件上传的逻辑:
MinIO 文件上传 MinIO 文件上传
mongo.png
)。通过以上实现,您可以轻松实现安全、高效的文件上传功能,同时减少服务器负载。
转载地址:http://kkffk.baihongyu.com/