npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

qhr-qiniu-upload-plugin

v3.0.0

Published

vue webpack 七牛云上传工具

Downloads

4

Readme

七牛云上传工具类

实例化

new QiniuUploadPlugin({
  publicPath: 'http://ptsy113ym.bkt.clouddn.com/', // 七牛云域名,自动替换 publicPath
  accessKey: '_Myja5YbUc-nuPb6YzReKNZxIjrW6m9BTbNFGPOE', // 个人中心,秘钥管理,AK
  secretKey: 'Uux98HyseDsjJqryuIi0kKH13GbViUwPXIizoA3Q', // 个人中心,秘钥管理,SK
  bucket: 'lqeshow', // 存储空间名称
  zone: 'Zone_z0', // 存储地区'Zone_'+'存储地区号'
  absolutePath: 'test/node/',
  // 可选参数:
  uploadHtml: true, // 默认为 false,设置为 true 会上传html在七牛云上。
  cover: true // 慎用!默认为 false,设置为 true 会覆盖掉已经保存在七牛云上的同名文件。
}),

源代码

const qiniu = require('qiniu');
const path = require('path');
const ora = require('ora');
// 上传文件到七牛云
class QiniuUploadPlugin {
  constructor(qiniuConfig) {
    if (
      !qiniuConfig ||
      !qiniuConfig.publicPath ||
      !qiniuConfig.accessKey ||
      !qiniuConfig.secretKey ||
      !qiniuConfig.bucket ||
      !qiniuConfig.zone
    ) {
      throw new Error('参数没有传递完全!');
    }
    // 保存用户传参
    this.qiniuConfig = qiniuConfig;
    // 创建的七牛认证信息
    this.qiniuAuthenticationConfig = {};
    // 鉴权
    this.qiniuAuthenticationConfig.mac = new qiniu.auth.digest.Mac(
      qiniuConfig.accessKey,
      qiniuConfig.secretKey
    );
    // 设置存储空间名称
    const options = {
      scope: qiniuConfig.bucket
    };
    // 创建上传token
    const putPolicy = new qiniu.rs.PutPolicy(options);
    this.qiniuAuthenticationConfig.uploadToken = putPolicy.uploadToken(
      this.qiniuAuthenticationConfig.mac
    );
    let config = new qiniu.conf.Config();
    // 存储空间对应的机房
    config.zone = qiniu.zone[qiniuConfig.zone];
    this.qiniuAuthenticationConfig.formUploader = new qiniu.form_up.FormUploader(
      config
    );
    this.cdnManager = new qiniu.cdn.CdnManager(this.qiniuAuthenticationConfig.mac);
  }
  apply(compiler) {
    compiler.hooks.compilation.tap('QiniuUploadPlugin', compilation => {
      compilation.outputOptions.publicPath = this.qiniuConfig.publicPath + this.qiniuConfig.absolutePath;
      this.absolutePath = compilation.outputOptions.path;
    });

    compiler.hooks.done.tapAsync('QiniuUploadPlugin', (data, callback) => {
      // 先返回构建结果,然后异步上传
      callback();
      let assetsPromise = [];
      const spinner = ora('开始上传七牛云...').start();
      Object.keys(data.compilation.assets).forEach(file => {
        // 上传非html文件
        if (!/.html$/.test(file) || this.qiniuConfig.uploadHtml) {
          assetsPromise.push(this.uploadFile(file));
        }
      });
      Promise.all(assetsPromise)
        .then(res => {
          spinner.succeed('七牛云上传完毕!');
          if(this.qiniuConfig.uploadHtml){
            //刷新index.html
            var urlsToRefresh = [
              this.qiniuConfig.publicPath + this.qiniuConfig.absolutePath + 'index.html'
            ];
            //刷新链接,单次请求链接不可以超过100个,如果超过,请分批发送请求
            this.cdnManager.refreshUrls(urlsToRefresh, function(err, respBody, respInfo) {
              if (err) {
                throw err;
              }
              console.log(respInfo.statusCode);
              if (respInfo.statusCode == 200) {
                console.log(respBody);
              }
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    });
  }
  uploadFile(filename, coverUploadToken) {
    const key = this.qiniuConfig.absolutePath + filename;
    const localFile = path.join(this.absolutePath || '', filename);
    return new Promise((resolve, reject) => {
      // 文件上传
      const spinner = ora(`上传文件${key}...`).start();
      const uploadToken = coverUploadToken
        ? coverUploadToken
        : this.qiniuAuthenticationConfig.uploadToken;
      const putExtra = new qiniu.form_up.PutExtra()
      this.qiniuAuthenticationConfig.formUploader.putFile(
        uploadToken,
        key,
        localFile,
        putExtra,
        (respErr, respBody, respInfo) => {
          if (respErr) {
            throw respErr;
          }
          if (respInfo.statusCode == 200) {
            resolve(respInfo);
            spinner.succeed(`文件:${key},上传成功!`);
          } else {
            if (
              this.qiniuConfig.cover &&
              (respInfo.status === 614 || respInfo.statusCode === 614)
            ) {
              spinner.fail(`文件:${key},已存在,尝试覆盖上传!`);
              resolve(
                this.uploadFile(filename, this.coverUploadFile(filename))
              );
            } else {
              spinner.fail(`文件:${key},上传失败!`);
              reject(respInfo);
            }
          }
        }
      );
    });
  }
  coverUploadFile(filename) {
    var options = {
      scope: this.qiniuConfig.bucket + ':' + this.qiniuConfig.absolutePath +filename
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    return putPolicy.uploadToken(this.qiniuAuthenticationConfig.mac);
  }
}

module.exports = QiniuUploadPlugin;