Node. Js server

Use Node.js + Express.js to implement the server

const express = require("express"); const app = express(); const axios = require('axios'); app.set('port', process.env.PORT || 8082); App.use (express.static(__dirname)); static(__dirname); static(__dirname); // start app.listen(app.get('port'), () => {console.log("http://localhost:" + app.get('port')); });

Base64, HMAC-SHA1 and MD5 are prepared to realize signature authentication

See:
http://docs.upyun.com/api/aut…

const crypto = require("crypto");

// MD5
function MD5(value) {
  return crypto
    .createHash("md5")
    .update(value)
    .digest("hex");
}

// Base64
function base64(value) {
  return Buffer.from(value).toString("base64");
}

// hmacsha1
function hmacsha1(secret, value) {
    return crypto.createHmac('sha1', secret).update(value, 'utf-8').digest().toString('base64');
}

Upload and delete interfaces

const date = new Date().toGMTString(); const bucketname = ""; // Space name const key = ""; // operator const secret = ""; // Upload app. Get ("/ API /token/ Upload ", req, res) => { let fileName = (Math.random() * 100000000) >>> 0; let expiration = ((Date.now() / 1000) >>> 0) + 30 * 60; // Expired time of the request in Unix UTC timestamp in seconds. Advice to 30 minutes http://docs.upyun.com/api/form_api/ let method = "POST"; let policy = base64( JSON.stringify({ bucket: bucketname, // "save-key": "/" + fileName + "{.suffix}", "save-key": "/{filename}{.suffix}", expiration: expiration }) ); let authorization = "UPYUN " + key + ":" + hmacsha1(MD5(secret), method + "&/" + bucketname + "&" + policy); res.json({ msg: "OK", code: 200, data: { authorization: authorization, policy: policy } }); }); // Delete app.get('/api/token/del', (req, res) => { let item = req.query.item; let method = "DELETE" let authorization = "UPYUN " + key + ":" + hmacsha1(MD5(secret), method + '&/' + bucketname + item + '&'+ date); axios({ url: upyunUrl + bucketname + item, method: 'DELETE', headers: { 'Authorization': authorization, 'Date': date } }).then(response => { res.json({ msg: "OK", code: 200, data: {} }); }).catch(err => { console.log('err', err) }) })

Cross-domain interface calls

const cors = require('cors');

// CORS @see https://github.com/expressjs/cors
app.use(cors());

The front end

The front end is implemented using Vue.js

The introduction of the Bootstrap CSS

< link rel = "stylesheet" type = "text/CSS" href = "https://unpkg.com/[email protected]/dist/css/bootstrap.css" > < script src="https://unpkg.com/axios/dist/axios.min.js"></script> <! -- HTML --> <div id="app"> <div class="card" style="margin: 50px auto; width: 300px;" > <div class="card-body"> <h5 class="card-title">UPYun Upload & Delete</h5> <div class="card-text"> <div class="form-group"> <label for="file">Upload</label> <input type="file" id="file" class="form-control-file" @change="onChange"> <div class="form-text text-muted"> <ul> <li v-for="(item, index) in files"> {{item}} <a href="javascript:;" @click="onDel(item, index)">Del</a> </li> </ul> </div> </div> </div> </div> </div> </div>

Introduce Vue.js, Axios

< script SRC = "https://unpkg.com/[email protected]/dist/vue.js" > < / script > < script src="https://unpkg.com/axios/dist/axios.min.js"></script>

JS

Const upUrl = 'http://v0.api.upyun.com/' // + space name, such as: http://v0.api.upyun.com/yun-temp const baseApi = 'http://localhost:8082/api/' let uploadInput; let app = new Vue({ el: '#app', data: { files: [] }, methods: { onChange: function () { getToken(token => { let formData = new FormData(); formData.append("file", uploadInput.files[0]) formData.append('policy', token.policy) formData.append("authorization", token.authorization) axios({ method: 'POST', url: upUrl, data: formData }).then(res => { res = res || {} if (res.status ! == 200) { console.log('error') return } let data = res.data || {} this.files.push(data.url) alert('Success') }).catch(err => { console.log(err); }); }); }, onDel: function (item, index) { this.files.splice(index, 1) axios.request({ url: baseApi + 'token/del', method: 'GET', params: { item: encodeURI(item) } }).then(res => { alert('Deleted.') }).catch(err => { console.log(err) }) } }, Mounted () {uploadInput = $('file')}}) function $(el) {return document.getElementById(el)}  function getToken (fn) { let token = window.localStorage.getItem('token'); token = JSON.parse(token) || {}; let nowTime = Date.now(); if (nowTime < token.expired && token.authorization && token.policy) { fn(token) return } axios({ method: 'get', url: baseApi + 'token/upload' }) .then(res => { let data = res.data || {} data = data.data || {} const authorization = data.authorization const policy = data.policy const expired = ((Date.now() / 1000) >>> 0) + 30 * 60; token = { authorization, policy, expired } fn(token) window.localStorage.setItem('token', JSON.stringify(token)) }); }

Program source code

https://github.com/givebest/UPyun-upload-delete-node.js

Reprinted please indicate the source:https://blog.givebest.cn/other/2018/10/27/upyun-upload-delete-node.js.html