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

node koa2實(shí)現(xiàn)上傳圖片并且同步上傳到七牛云存儲(chǔ)

 更新時(shí)間:2017年07月31日 11:03:32   作者:Naice Blog  
這篇文章主要介紹了node koa2實(shí)現(xiàn)上傳圖片并且同步上傳到七牛云存儲(chǔ),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

因?yàn)樯?jí)到新的node版本,之前的通過(guò)很多上傳圖片的方式都已經(jīng)不適用了,所以自己就寫(xiě)了一個(gè)對(duì)于 koa2上傳圖片的小demo,記錄一下心得。

廢話(huà)不多說(shuō),下面直接上代碼,里面都有注釋。

const Koa = require('koa');
const route = require('koa-route');
const serve = require('koa-static');
const inspect = require('util').inspect
const path = require('path')
const os = require('os')
const fs = require('fs')
const Busboy = require('busboy')
const qiniu = require('qiniu')
const qiniuConfig = require('./qiniuconfig')

 
const app = new Koa();

app.use(serve(__dirname + '/public/'));

 
// 寫(xiě)入目錄
const mkdirsSync = (dirname) => {
 if (fs.existsSync(dirname)) {
  return true
 } else {
  if (mkdirsSync(path.dirname(dirname))) {
   fs.mkdirSync(dirname)
   return true
  }
 }
 return false
}

function getSuffix (fileName) {
 return fileName.split('.').pop()
}

// 重命名
function Rename (fileName) {
 return Math.random().toString(16).substr(2) + '.' + getSuffix(fileName)
}
// 刪除文件
function removeTemImage (path) {
 fs.unlink(path, (err) => {
  if (err) {
   throw err
  }
 })
}
// 上傳到七牛
function upToQiniu (filePath, key) {
 const accessKey = qiniuConfig.accessKey // 你的七牛的accessKey
 const secretKey = qiniuConfig.secretKey // 你的七牛的secretKey
 const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)

 const options = {
  scope: qiniuConfig.scope // 你的七牛存儲(chǔ)對(duì)象
 }
 const putPolicy = new qiniu.rs.PutPolicy(options)
 const uploadToken = putPolicy.uploadToken(mac)

 const config = new qiniu.conf.Config()
 // 空間對(duì)應(yīng)的機(jī)房
 config.zone = qiniu.zone.Zone_z2
 const localFile = filePath
 const formUploader = new qiniu.form_up.FormUploader(config)
 const putExtra = new qiniu.form_up.PutExtra()
 // 文件上傳
 return new Promise((resolved, reject) => {
  formUploader.putFile(uploadToken, key, localFile, putExtra, function (respErr, respBody, respInfo) {
   if (respErr) {
    reject(respErr)
   }
   if (respInfo.statusCode == 200) {
    resolved(respBody)
   } else {
    resolved(respBody)
   }
  })
 })

}

// 上傳到本地服務(wù)器
function uploadFile (ctx, options) {
 const _emmiter = new Busboy({headers: ctx.req.headers})
 const fileType = options.fileType
 const filePath = path.join(options.path, fileType)
 const confirm = mkdirsSync(filePath)
 if (!confirm) {
  return
 }
 console.log('start uploading...')
 return new Promise((resolve, reject) => {
  _emmiter.on('file', function (fieldname, file, filename, encoding, mimetype) {
   const fileName = Rename(filename)
   const saveTo = path.join(path.join(filePath, fileName))
   file.pipe(fs.createWriteStream(saveTo))
   file.on('end', function () {
    resolve({
     imgPath: `/${fileType}/${fileName}`,
     imgKey: fileName
    })
   })
  })

  _emmiter.on('finish', function () {
   console.log('finished...')
  })

  _emmiter.on('error', function (err) {
   console.log('err...')
   reject(err)
  })

  ctx.req.pipe(_emmiter)
 })
}



app.use(route.post('/upload', async function(ctx, next) {

  const serverPath = path.join(__dirname, './uploads/')
 // 獲取上存圖片
 const result = await uploadFile(ctx, {
  fileType: 'album',
  path: serverPath
 })
 const imgPath = path.join(serverPath, result.imgPath)
 // 上傳到七牛
 const qiniu = await upToQiniu(imgPath, result.imgKey)
 // 上存到七牛之后 刪除原來(lái)的緩存圖片
 removeTemImage(imgPath)
 ctx.body = {
  imgUrl: `http://xxxxx(你的外鏈或者解析后七牛的路徑)/${qiniu.key}`
 }
}));
 
app.listen(3001);

console.log('listening on port 3001');

然后在同一級(jí)目錄下,創(chuàng)建一個(gè)public文件夾,然后在下面新建一個(gè) index.html,因?yàn)槲覀兩厦嬉呀?jīng)把這個(gè)文件夾設(shè)置為靜態(tài)訪問(wèn)文件夾了, public/index.html 的代碼為

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <input id="btn1" type="file" name="file"/> 
 <input id="btn2" type="submit" value="提交"/>
</body>
<script>
  
  var btn1 = document.querySelector('#btn1')
  var btn2 = document.querySelector('#btn2')
  var file = null
  btn1.addEventListener('change', function(e){
    file = e.target.files[0]
  })

  btn2.onclick = function(){
  var _data = new FormData();
  _data.append('file', file);
  xhr(_data)
  }

  var xhr = function(formdata){
    var xmlHttp = new XMLHttpRequest(); 

    xmlHttp.open("post","http://127.0.0.1:3001/upload", true); 
     
    xmlHttp.send(formdata);

    xmlHttp.onreadystatechange = function(){ 
     if(xmlHttp.readyState==4){ 
       if(xmlHttp.status==200){ 
         var data = xmlHttp.responseText; 
         console.log(data); 
       } 
     }
    }
  }
</script>
</html>

選擇好圖片,然后點(diǎn)擊提交,就可以上傳到你的七??臻g啦!

源代碼在 github: https://github.com/naihe138/koa-upload

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Node.js 異步異常的處理與domain模塊解析

    Node.js 異步異常的處理與domain模塊解析

    本篇文章主要介紹了Node.js 異步異常的處理與domain模塊解析,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • Nodejs中執(zhí)行的shell命令的代碼分享

    Nodejs中執(zhí)行的shell命令的代碼分享

    雖然nodejs運(yùn)行時(shí)提供了和OS交互的諸多API命令,但是有些操作(例如:特定系統(tǒng)信息獲取)還是使用shell命令更加方便一些,下面就跟隨小編一起來(lái)看看有哪些是宜在nodejs中執(zhí)行的shell代碼吧
    2024-02-02
  • nodejs實(shí)現(xiàn)UDP組播示例方法

    nodejs實(shí)現(xiàn)UDP組播示例方法

    這篇文章主要介紹了nodejs實(shí)現(xiàn)UDP組播示例方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • npm的安裝與使用

    npm的安裝與使用

    這篇文章介紹了npm的安裝與使用,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • 詳解node.js搭建代理服務(wù)器請(qǐng)求數(shù)據(jù)

    詳解node.js搭建代理服務(wù)器請(qǐng)求數(shù)據(jù)

    本篇文章主要介紹了詳解node.js搭建代理服務(wù)器請(qǐng)求數(shù)據(jù),具有一定的參考價(jià)值,有興趣的可以了解一下。
    2017-04-04
  • nodejs模塊系統(tǒng)源碼分析

    nodejs模塊系統(tǒng)源碼分析

    這篇文章主要介紹了nodejs模塊系統(tǒng)源碼分析,對(duì)nodejs感興趣的同學(xué),可以參考下
    2021-05-05
  • nodejs中實(shí)現(xiàn)sleep功能實(shí)例

    nodejs中實(shí)現(xiàn)sleep功能實(shí)例

    這篇文章主要介紹了nodejs中實(shí)現(xiàn)sleep功能實(shí)例,本文講解了sleep功能的開(kāi)發(fā)過(guò)程和使用效果及性能測(cè)試,需要的朋友可以參考下
    2015-03-03
  • node.js中的fs.symlink方法使用說(shuō)明

    node.js中的fs.symlink方法使用說(shuō)明

    這篇文章主要介紹了node.js中的fs.symlink方法使用說(shuō)明,本文介紹了fs.symlink的方法說(shuō)明、語(yǔ)法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下
    2014-12-12
  • Nodejs腳本實(shí)現(xiàn)批量修改文件

    Nodejs腳本實(shí)現(xiàn)批量修改文件

    當(dāng)我們想要更改一下所有的文件,如何可以在修改到這些文件的同時(shí)又能實(shí)現(xiàn)節(jié)省時(shí)間呢,通過(guò)這篇文章我們將來(lái)學(xué)習(xí)一下怎么通過(guò)這個(gè)腳本來(lái)實(shí)現(xiàn)這個(gè)功能,希望對(duì)大家有所幫助
    2023-11-11
  • Nodejs之Express中間件的分類(lèi)介紹

    Nodejs之Express中間件的分類(lèi)介紹

    這篇文章主要介紹了Nodejs之Express中間件的分類(lèi),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-12-12

最新評(píng)論