koa2實現上傳圖片,而且同步上傳到七牛雲存儲

由於升級到新的node版本,以前的經過不少上傳圖片的方式都已經不適用了,因此本身就寫了一個對於 koa2上傳圖片的小demo,記錄一下心得。html

廢話很少說,下面直接上代碼,裏面都有註釋。node

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

 
// 寫入目錄
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 // 你的七牛存儲對象
  }
  const putPolicy = new qiniu.rs.PutPolicy(options)
  const uploadToken = putPolicy.uploadToken(mac)

  const config = new qiniu.conf.Config()
  // 空間對應的機房
  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)
      }
    })
  })

}

// 上傳到本地服務器
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)
  // 上存到七牛以後 刪除原來的緩存圖片
  removeTemImage(imgPath)
  ctx.body = {
    imgUrl: `http://xxxxx(你的外鏈或者解析後七牛的路徑)/${qiniu.key}`
  }
}));
 
app.listen(3001);

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

而後在同一級目錄下,建立一個public文件夾,而後在下面新建一個 index.html,由於咱們上面已經把這個文件夾設置爲靜態訪問文件夾了, public/index.html 的代碼爲git

<!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>

選擇好圖片,而後點擊提交,就能夠上傳到你的七牛空間啦!github

文章博客地址: http://blog.naice.me/articles緩存

ps: 若是對你有幫助請隨手丟一個 start 哦服務器

源代碼在 github: https://github.com/naihe138/k...app

相關文章
相關標籤/搜索