🐕文件上传的简介:
我们把头像上传到应用web服务器中,使用户能在网页前端访问到图片信息。
🐟上传图片的示意图:
用户点击上传图片,把图片上传到应用web服务器中,我们把图片部署到OSS云服务器中,OSS云服务器会把图片信息返回一个外链,用户访问外链即可看到图片信息。
🐟 为什么我们要使用OSS:
因为如果把图片视频等文件上传到自己的应用的web服务器,在读取图片的时候会占用比较多的资源。影响应用服务器的性能。所有我们一般使用OSS(Object Storage Service 对象存储服务)存储图片或视频。
这里我们使用的是七牛云,免费的云服务平台。
🐕七牛云的使用:
🐟:注册账号
🐟:进入控制台
🐟:创建存储空间
选择一个离自己所在地区比较近的区域
填写存储名称
访问控制 :如果选择公开的话,就是其他人可以访问到的,一般选公开;
🐟: 可进入开发者中心
选择对象存储:
🐟: 进入阅读详细文档:
详细文档里面有文件上传的API。
🐕:文件上传的具体实现:
🐟:在项目中添加七牛云依赖:
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.10.99]</version>
</dependency>
🐟:上传图片我们一般使用数据流上传:
🐟: 查找密钥:
🐟: 复制文档给的demo进行测试:
以下代码修改了七牛云官方提供的文档代码:(更适合使用)
package com.nice;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.FileInputStream;
import java.io.InputStream;
@SpringBootTest
@ConfigurationProperties(prefix = "oss")
public class OSSTest {
private String accessKey;
private String secretKey;
private String bucket;
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
@Test
public void testOSS(){
//构造一个带指定 Region 对象的配置类 autoRegion()自动寻找地区
Configuration cfg = new Configuration(Region.autoRegion());
cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;
try {
InputStream inputStream = new FileInputStream("E:\\图片及视频\\微信\\2.jpg");
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(inputStream,key,upToken,null, null);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
} catch (Exception ex) {
//ignore
}
}
}
🐟:测试结果:
文章仅供参考,请勿商用.....