欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

又拍云 Node.js 實(shí)現(xiàn)文件上傳、刪除功能

 更新時(shí)間:2018年10月28日 09:22:14   作者:givebest  
這篇文章主要介紹了又拍云 Node.js 實(shí)現(xiàn)文件上傳、刪除功能,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

Node.js 服務(wù)端

使用 Node.js + Express.js 實(shí)現(xiàn) 服務(wù)端

const express = require("express");
const app = express();
const axios = require('axios');
app.set('port', process.env.PORT || 8082);
// 靜態(tài)資源目錄,這里放在了根目錄,生產(chǎn)環(huán)境不允許這樣
app.use(express.static(__dirname));
// 啟動(dòng)一個(gè)端口為 8082 的服務(wù)器
app.listen(app.get('port'), () => {
 console.log("http://localhost:" + app.get('port'));
});

準(zhǔn)備 Base64、HMAC-SHA1、MD5 實(shí)現(xiàn)簽名認(rèn)證

詳見(jiàn):http://docs.upyun.com/api/authorization/#_5

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');
}

上傳、刪除接口

const date = new Date().toGMTString();
const bucketname = ""; // 空間名
const key = ""; // 操作員
const secret = ""; // 密碼
const upyunUrl = 'http://v0.api.upyun.com/'
// Upload
app.get("/api/token/upload", (req, res) => {
 let fileName = (Math.random() * 100000000) >>> 0;
 let expiration = ((Date.now() / 1000) >>> 0) + 30 * 60; // 請(qǐng)求的過(guò)期時(shí)間,UNIX UTC 時(shí)間戳,單位秒。建議設(shè)為 30 分鐘 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)
 })
})

跨域接口調(diào)用

const cors = require('cors');

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

前端

前端使用 Vue.js 實(shí)現(xiàn)

引入 Bootstrap.css

<link rel="stylesheet" type="text/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:;" rel="external nofollow" @click="onDel(item, index)">Del</a>
        </li>
      </ul>
     </div>
    </div>
   </div>
  </div>
 </div>
</div>

引入 Vue.js、Axios

<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

JS

const upUrl = 'http://v0.api.upyun.com/' // +空間名,如: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')
   }
  })
  // DOM 獲取元素
  function $ (el) {
   return document.getElementById(el)
  }
  // 獲取 token
  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))
   });
  }

項(xiàng)目源碼

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

總結(jié)

以上所述是小編給大家介紹的又拍云 Node.js 實(shí)現(xiàn)文件上傳、刪除,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!

相關(guān)文章

  • nodejs如何獲取時(shí)間戳與時(shí)間差

    nodejs如何獲取時(shí)間戳與時(shí)間差

    本文詳細(xì)介紹了nodejs獲取時(shí)間戳與時(shí)間差的多種方法,對(duì)平時(shí)nodejs的使用很有幫助,下面一起來(lái)看看吧。
    2016-08-08
  • 基于Node-red的在線評(píng)語(yǔ)系統(tǒng)(可視化編程,公網(wǎng)訪問(wèn))

    基于Node-red的在線評(píng)語(yǔ)系統(tǒng)(可視化編程,公網(wǎng)訪問(wèn))

    Node-Red是IBM公司開(kāi)發(fā)的一個(gè)可視化的編程工具,在網(wǎng)頁(yè)內(nèi)編程,主要是拖拽控件,代碼量很小,這篇文章主要介紹了基于Node-red的在線評(píng)語(yǔ)系統(tǒng)(可視化編程,公網(wǎng)訪問(wèn)),需要的朋友可以參考下
    2022-01-01
  • NodeJs下的測(cè)試框架Mocha的簡(jiǎn)單介紹

    NodeJs下的測(cè)試框架Mocha的簡(jiǎn)單介紹

    本篇文章主要介紹了NodeJs下的測(cè)試框架Mocha的簡(jiǎn)單介紹,是目前最為流行的javascript框架之一,在本文我們重點(diǎn)介紹它在NodeJs上的使用。有興趣的可以了解一下。
    2017-02-02
  • 淺談Nodejs觀察者模式

    淺談Nodejs觀察者模式

    這篇文章主要介紹了淺談Nodejs觀察者模式的相關(guān)資料,需要的朋友可以參考下
    2015-10-10
  • Node.JS段點(diǎn)續(xù)傳:Nginx配置文件分段下載功能的實(shí)現(xiàn)方法

    Node.JS段點(diǎn)續(xù)傳:Nginx配置文件分段下載功能的實(shí)現(xiàn)方法

    在Node.JS中可以配置這個(gè)標(biāo)簽來(lái)實(shí)現(xiàn)文件的分段下載。這篇文章給大家介紹了Node.JS段點(diǎn)續(xù)傳:Nginx配置文件分段下載功能的實(shí)現(xiàn)方法,需要的朋友參考下吧
    2018-03-03
  • Node.js讀取文件操作教程示例

    Node.js讀取文件操作教程示例

    這篇文章主要為大家介紹了Node.js讀取文件教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11
  • Node.js Stream ondata觸發(fā)時(shí)機(jī)與順序的探索

    Node.js Stream ondata觸發(fā)時(shí)機(jī)與順序的探索

    今天小編就為大家分享一篇關(guān)于Node.js Stream ondata觸發(fā)時(shí)機(jī)與順序的探索,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-03-03
  • Express本地測(cè)試HTTPS的示例代碼

    Express本地測(cè)試HTTPS的示例代碼

    這篇文章主要介紹了Express本地測(cè)試HTTPS的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-06-06
  • Node配合WebSocket做多文件下載以及進(jìn)度回傳

    Node配合WebSocket做多文件下載以及進(jìn)度回傳

    這篇文章主要介紹了Node配合WebSocket做多文件下載以及進(jìn)度回傳功能,本文通過(guò)實(shí)例代碼效果截圖給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2019-11-11
  • node.js去水印方法實(shí)例分析

    node.js去水印方法實(shí)例分析

    這篇文章主要介紹了node.js去水印方法,結(jié)合實(shí)例形式分析了node.js基于第三方平臺(tái)實(shí)現(xiàn)去水印的相關(guān)交互與操作技巧,需要的朋友可以參考下
    2023-04-04

最新評(píng)論