preface
When using Vue to do background management system, there is a requirement is to upload pictures, files. In order to save memory and facilitate management, we usually store large files to the cloud server, store the address returned by the cloud server to our background server, and replace pictures and files with strings. So how does this work? Come and see how to do it
First, why to store large files in the cloud server?
- Cloud servers are much more powerful than their own servers in computing capacity, storage space and other aspects
- The size of the image is much larger than the URL string
- Reduce the stress on your server
- After registering with the cloud server, you can get free storage space at a low cost
How to apply for a cloud server?
Take Tencent Cloud as an example. Tencent cloud official website
1. Set up an account
- You can use wechat to scan the code and then click to register
- Fill in personal Information
- Real name authentication (face brushing)
2. Apply for object storage
After successful registration, search on Tencent cloud home pageObject storage
Then click use now, and it will remind you that it is not openCos service
After agreeing to the agreement, the service will be opened.Then click Create bucket to select your location.
3. Enable cross-domain access to CORS
Click the bucket nameClick cross domain Access CORS Settings in Security Management.Click Add Rule, test phase, first make all domain names accessible.
4. Access key
To upload files to the cloud server through code, you need an access key.After the search is complete, follow the prompts and save the key.Tencent Cloud Document:Object storage
How to use code to upload files to the cloud server?
1. Download third-party packages
To use cos-js-SDK-V5, you can use NPM install cos-js-sdK-v5-s to download it into the Vue project.
2. Instantiate the COS object
This is where you need the key, so just copy it.
The code is as follows (example) :
// const COS = require(' cos-js-sdK-v5 ') const COS = new COS({SecretId: 'XXX ', // identity ID SecretKey:' XXX '// identity key}) copy codeCopy the code
3. Upload using THE API provided by COS
This API requires basic information about object storage. You can use the following figure.
The code is as follows (example) :
Write an upload method in the Methods section of the Vue project and use the putObject provided by COS to complete the upload action.
Cos. putObject({Bucket: 'XXXXXX ', /* Bucket */ Region:' XXXX ', /* Bucket location */ Key: Res.file. name, /* file name */ StorageClass: 'STANDARD', // Upload mode, STANDARD mode Body: Res.file // Upload file object}, (err, Data) = > {the console. The log (err | | data) / / upload success after the if (data. StatusCode = = = 200) {/ / will return to the address of the server storage down after a successful upload const url = 'https://${data.Location}' console.log(' cloud server returns address: '+ URL)}})Copy the code