环境说明
Jdk1.8
Maven3.6.3
IDEA2022
OSS简介
OSS的英文全称是Object Storage Service,翻译成中文就是对象存储服务。OSS非常适合存储静态资源,提供HTTP链接的方式来访问到静态资源,例如图片,减轻业务服务器存储静态文件的压力。
这里选择七牛云 对象存储服务来实现OSS功能。
准备工作
注册登录七牛云:七牛云 | 一站式场景化智能视频云
新建存储空间:
新建密钥:
点击头像-->个人中心
密钥管理-->创建密钥,得到AK和SK,后面编码有用。
七牛云文档地址:Java SDK_SDK 下载_对象存储 - 七牛开发者中心
最简单的就是上传本地文件案例:
数据流上传案例:
步骤
新建SpringBoot工程
新建springboot工程qiniuyundemo
依赖如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.10.99]</version>
</dependency>
</dependencies>
1.实现简单的文件上传
新建包:
在启动程序QiniuyundemoApplication.java所在的包下新建一个upload包
新建类:
在upload包下,新建Upload类,实现简单的文件上传,完整代码如下:
package com.example.qiniuyundemo.upload;
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;
/**
* 文件上传
*/
public class Upload {
public static void main(String[] args) {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region2());
cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = "xxxxxxxx";//xxxxxxxx换成七牛云的AK密钥
String secretKey = "xxxxxxxx";//xxxxxxxx换成七牛云的SK密钥
String bucket = "xxxxxxxx";//xxxxxxxx换成七牛云的空间名称
//指定需要上传的文件路径
String localFilePath = "D:\\testpic\\bdd2.jpeg";
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(localFilePath, key, upToken);
//解析上传成功的结果
// DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
// System.out.println(putRet.key);
// System.out.println(putRet.hash);
System.out.println(response);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
}
}
运行Upload代码,结果如下:
查看七牛云的空间管理-->选择需要查看的空间名称-->点击文件管理,查看到上传的文件,如下:
2.配合前端实现文件上传
新建包,新建类,新建前端目录及文件,最终目录结构如下:
代码如下:
控制类
package com.example.qiniuyundemo.controller;
import com.example.qiniuyundemo.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Controller
public class UploadController {
@Autowired
UploadService uploadService;
@RequestMapping("/upload")
@ResponseBody
public String upload(MultipartFile file) throws IOException {
String filename = file.getOriginalFilename();
String date = DateTimeFormatter.ofPattern("yyyy/MM/dd/").format(LocalDateTime.now());
filename = date + System.currentTimeMillis()+filename.substring(filename.lastIndexOf("."));
return uploadService.upload(file.getInputStream(), filename);
}
}
服务接口类
package com.example.qiniuyundemo.service;
import java.io.InputStream;
public interface UploadService {
/**
* 上传服务
* @param inputStream
* @param fileName
* @return
*/
String upload(InputStream inputStream, String fileName);
}
服务实现类
参照文档的数据流上传代码
package com.example.qiniuyundemo.service.impl;
import com.example.qiniuyundemo.service.UploadService;
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.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
/**
* 上传服务实现类
*/
@Service
public class UploadServiceImpl implements UploadService {
@Override
public String upload(InputStream inputStream, String fileName) {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region2());
cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = "xxxxxxxx";//xxxxxxxx换成七牛云的AK密钥
String secretKey = "xxxxxxxx";//xxxxxxxx换成七牛云的SK密钥
String bucket = "xxxxxxxx";//xxxxxxxx换成七牛云的空间名称
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = fileName;
String result = null;
try {
// byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
// ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
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);
if(response.statusCode==200){
result = "http://xxxxxxx.com/"+ fileName;//http://xxxxxxx.com/换成七牛云提供的测试域名或者空间绑定的域名
}
} 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
}
return result;
}
}
upload.html文件
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>OOS文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
修改Springboot上传文件大小配置
application.properties
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart-request-size=100MB
运行QiniuyundemoApplication类
测试
浏览器访问
http://localhost:8080/upload.html
点击选择文件,并提交,
上传文件成功后,页面返回文件的访问链接如下:
可以使用浏览器访问返回的链接,能显示上传的图片。
查看七牛云的空间管理,进入对于的空间名称,点击文件管理,找到上传的文件。
完成!enjoy it!