This is the first day of my August challenge
7 Niuyun picture upload
Qiuniuyun provides free CDN storage space. We can make use of the functions provided by Qiuniuyun, customize our own graph bed, customize our application static resource server and so on.
Static resources can be uploaded in two ways: 1. Front-end upload 2. Server upload
Next, I will refer to the SDK document of Qiuniuyun official website to realize two uploading methods respectively.
Preparation: First register a seven Ox account (register address) and log into the console to get a valid AccessKey and SecretKey (get address).
First, front-end upload
qiniu-js | SDK
- Add the dependent
npm install qiniu-js
import * as qiniu from ‘qiniu-js’
- Directions for use
The qiniu.upload returns an Observable that controls uploads. An Observable can subscribe to an observer, which starts uploads, and returns a subscription object. This object has an unsubscribe method that unsubscribes and terminates the upload.
- code
constObservable = qiniu.upload(file, key, token, putExtra, config);const observer = {
next(res){
// ...
},
error(err){
// ...
},
complete(res){
// ...}}const subscription = observable.subscribe(observer) // Upload started
// or
const subscription = observable.subscribe(next, error, complete) // This is ok
subscription.unsubscribe() // Upload cancelled
Copy the code
File: File object Key: file name Token: The token needs to be used by the backend. For details, see the following back-end service codes to obtain the token. See the following figure for the configuration of config and putExtra
2. Back-end upload
1.Java
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2. 0.7.299.]</version>
</dependency>
Copy the code
- Access token
@RestController
@RequestMapping("/qiniu")
public class UtilController {
public String accessKey = "B_4zonc-5muZd9dijUnUKrdxvBJ0-hdUYz5fWU8p";
public String secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
public String bucket = "levenx";
@GetMapping("/token")
public Result uploadToken(a) {
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
returnResult.newResult(upToken); }}Copy the code
2.Node
npm install qiniu
Copy the code
- Access token
var accessKey = 'your access key';
var secretKey = 'your secret key';
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
var options = {
scope: bucket,
expires: 7200
};
var putPolicy = new qiniu.rs.PutPolicy(options);
var uploadToken=putPolicy.uploadToken(mac);
Copy the code