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

koa2-file-uploader

v0.3.0

Published

koa middleware use upload file

Downloads

37

Readme

koa2-file-uploader

koa2 middleware/function to upload file, supports local, oss, cos, obs, azure, aws stores.

This package is a fork from dzy321/file-upload allowing to use the package to upload files with/without using the package as a middleware. (Special thanks to dzy321, for creating an all-in-one package to upload to different stores)

With my version, you can use this package for uploading your custom-parsed files & files your server downloads from other websites, etc... (it lets you give a file)

Install

npm i koa2-file-uploader

Usage As Upload Function

const { imageUpload } = require('koa2-file-uploader');

const options = require('./myConfig.js'); // see below for creating Options

async function uploadMyTestFile() { // const uploadMyTestFile = async() => {
  const testFile = new File(["foo"], "foo.txt", {
    type: "text/plain",
  });
  const { result, error }  = await uploader(testFile);
  if (error) {
    console.log(`${error.status}: ${error.message}`);
  } else {
    console.log('successfully uploaded files: ', JSON.stringify(result));
  }
}

async function uploadMyTestFiles() {
  const testFiles = ['aaa', 'bbb', 'ccc', 'ddd', 'eee'].map((title) =>
    new File(["I'm a test file :P", title], `${title}.txt`,
      { type: "text/plain" }));
}

async function test() {
  await uploadMyTestFile();
  console.log('----------');
  await uploadMyTestFiles();
}

test();

File Object

// file or each file in files is in below format
var file = {
  file: binary, // binary image data
  filename: string, // photo.png
  mimeType: string, // image/png
  path: string, // path of tmp file location  
  
}

Usage As Middleware

const Koa = require('koa');
const app = new Koa();

const { imageUploadMiddleware } = require('koa2-file-uploader');

const options = require('./myConfig.js'); // see below for creating Options

app.use(imageUploadMiddleware(options));

Options

General Options:

options = {
  "storeDir": "uploadsFolder", // to upload to /uploadsFolder/...
  "subDir": (file) => str || { date: true } || "customStr" || new Date() || null,
  // default is { date: true }
  /* dynamic subDir options (different subDir for each file)
   * (file) => str: uploads to /storeDir/str/... (File is parsed File) 
   * { date: true } (default) => uploads to /storeDir/yyyy/mm/dd/... (current date)
   * { date: format } => uploads to /storeDir/{format}/... (current date)
   * { random: true } => uploads to /storeDir/{randomHex}/...
   */
  /* static subDir options (same subDir for each file)
   * str: uploads to /storeDir/str/...
   * Date: uploads to /storeDir/yyyy/mm/dd... (given date object such as new Date())
   * null: uploads to /storeDir/... (You must explicitly give null to omit sub directory)
   */
  "mimetypes": ['image/png','image/bmp'], // accept only those
  // for a list of mimetypes http://www.freeformatter.com/mime-types-list.html
  "filename": (file) => str || null
  // (file) => str uploads to /storeDir/subDir/str (you must provide extension in function return)
  // null (default)
}

Route Path for Middleware:

options = {
  "url": '/api/upload'
}

Provider Specific Options:

  • support upload to local dir
options = {
  "url": "/api/upload",
  "provider": "local",
  "mimetypes": ["image/png","image/bmp"],
  "storeDir": "images",
  "folder": "uploads/media",
  "urlPath": "static" // base for urls it returns
  // file is put to ${folder}/${storeDir}/${subDir}/${file}
  // result is returned as ${urlPath}/${storeDir}/${subDir}/${file}
  // so in that example, image is uploaded to /uploads/media/images/abcdefg.png
  // and the result is returned as { body: ['/static/images/abcdefg.png'] } 
}
  • support upload to oss
options["upload"] = {
  "url": '/api/upload',
  "provider": "oss",
  "storeDir": 'xxx',
  "mimetypes": ['image/png','image/bmp'],
  "accessKeyId": "key",
  "accessKeySecret": "secret",
  "bucket": "terminus-designer",
  "region": "oss-cn-hangzhou",
  "filename": (file) => `${new Date().getTime()}-${file.filename}`, // default null
  "targetProtocol": "http", // default null
  "attachment": true // default null
}
  • support upload to cos
options["upload"] = {
  "url": '/api/upload',
  "provider": "cos",
  "storeDir": 'xxx',
  "bucket": "b2b",
  "appId": "xxx",
  "secretID": "xxx",
  "secretKey": "xx",
  "region": "gz"
}
  • support upload to obs
options["upload"] = {
  "url": '/api/upload',
  "provider": "obs",
  "bucket": "****",
  "accessKeyId": "****",
  "accessKeySecret": "****",
  "server": "****"
}
  • support upload to azure
options["upload"] = {
  "url": '/api/upload',
  "provider": "azure", 
  "container": "xxxx",
  "account": "xxxx",
  "connectionString": "xxxx",
}
  • support upload to aws
options["upload"] = {
  "url": '/api/upload',
  "endpoint": "http://localhost:801",
  "provider": "aws", 
  "bucket": "****",
  "accessKeyId": "****",
  "secretAccessKey": "****",
  "s3ForcePathStyle": true, // minio support
  "signatureVersion": "v4", // minio support,
  "isPublic": false // true adds ACL: public-read
}

Requirements

  • Node v6.0+