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

@devcodes-sdk/server-upload

v1.1.0

Published

The `devcodes-sdk/server-upload` provides functionality for handling file uploads, interacting with Amazon S3, and optimizing image files. This document explains how to install and use the provided functions.

Downloads

26

Readme

DevCodes-SDK Upload Agent 🚀

The devcodes-sdk/server-upload provides functionality for handling file uploads, interacting with Amazon S3, and optimizing image files. This document explains how to install and use the provided functions.

Note: This version is still in development and testing (beta). It may contain bugs and is not yet considered production-ready.

Note: If you are encountering an AccessDenied error with isPrivateAccess=false, please review your bucket policy to ensure that the bucket is publicly accessible. To enable public access, navigate to the bucket's permissions tab and click on the "Block public access" settings. Then, disable the "Block all public access" option and save the changes.

Features

  • Multiple S3 Clients: Manage multiple S3 configurations and buckets within a single instance.
  • Image Optimization: Automatically optimize images before uploading them to S3.
  • Public/Private File Uploads: Support for uploading files with different access levels (public or private).
  • Pre-Signed URLs: Generate pre-signed URLs for secure access to files in S3.
  • File Deletion: Easily delete files from S3.

Installation

To install the package, run:

npm i @devcodes-sdk/server-upload

Setup

Initialization

First, import and initialize the UploadAgent with the necessary options:

import UploadAgent from "@devcodes-sdk/server-upload";

const uploadAgent = new UploadAgent({
  s3: [
    {
      bucketName: "your-bucket-name",
      accessKey: "",
      bucketRegion: "",
      secretKey: "",
      isPrivateAccess: true, // Note: This setting does not override inline access permissions.
    },
  ],
}).create();

export const {
  uploadMiddleware,
  uploadFilesFromRequest,
  uploadFileToS3,
  generatePreSignedUrl,
  deleteFileFromS3,
} = uploadAgent;

Multer Middleware - (uploadMiddleware)

This middleware handles file uploads with the following features:

Parameters:

  • allowedMimes (Array): Specifies the allowed MIME types for uploaded files. For example, ["image/png"] restricts uploads to PNG images only.
  • maxSize (Number): Defines the maximum allowed file size in bytes. For instance, 10 * 1024 * 1024 sets a limit of 10 megabytes.

Single vs. Array Uploads:

  • Single Upload: When using .single("file"), the uploaded file is accessed via req.file.
  • Array Uploads: When using .array("files"), the uploaded files are accessed via req.files.

The middleware returns the uploaded file(s) as a buffer, depending on whether a single file or multiple files are uploaded.

app.post(
  "/upload",
  uploadMiddleware({
    allowedMimes: ["image/png"],
    maxSize: 10 * 1024 * 1024,
  }).single("avatar"),
  async (req, res) => {
    try {
      // if .single("") is used, req.file will contain the file
      const file = req.file;

      // if .array("") is used, req.files will contain the files
      const files = req.files;
    } catch (error) {
      res.status(400).json({ message: error });
    }
  }
);

Upload Files from Request - (uploadFilesFromRequest)

Processes files uploaded via an HTTP request and uploads them to S3.

  • Required: uploadMiddleware

Parameters:

  • req: (Express Request Object): The HTTP request object.
  • folder: (String): S3 folder path. // Node: It must start with '/' and not end with '/'
  • isPrivateAccess: (Boolean): Whether the file should be privately accessible.
  • bucketName: (String): S3 bucket name.
  • imageOptimization: (Boolean): Whether to optimize images.
app.post('/upload', uploadMiddleware.single('avatar'), async (req, res) => {
  try {
    const result = await uploadFilesFromRequest({
      req,
      folder: '/uploads',
      isPrivateAccess: true,
      bucketName: 'your-bucket-name',
      imageOptimization: true
    });
    res.json(result);
  } catch (error) {
    res.status(500).send(error.message);
  }
});

Upload File to S3 - (uploadFileToS3)

Uploads a file directly to S3.

Parameters:

  • file: (Buffer): File buffer.
  • folder: (String): S3 folder path. // Node: It must start with '/' and not end with '/'
  • isPrivateAccess: (Boolean): Whether the file should be privately accessible.
  • bucketName: (String): S3 bucket name.
  • imageOptimization: (Boolean): Whether to optimize images.
uploadFileToS3({
  file: fileBuffer,
  folder: '/uploads',
  isPrivateAccess: true,
  bucketName: 'your-bucket-name',
  imageOptimization: false
}).then(result => {
  console.log(result);
}).catch(error => {
  console.error(error);
});

Generate PreSignedURL - (generatePreSignedUrl)

Generates a pre-signed URL for accessing a file in S3.

Parameters:

  • key: (String): S3 file key.
  • bucketName: (String): S3 bucket name.
  • expiresIn: (Number): URL expiration time in seconds.
generatePreSignedUrl({
  key: '/uploads/b5c9fecc-1dd0-457f-b55d-dba223050b27',
  bucketName: 'your-bucket-name',
  expiresIn: 60 // URL valid for 60 seconds
}).then(url => {
  console.log(url);
}).catch(error => {
  console.error(error);
});

Delete File from S3 - (deleteFileFromS3)

Deletes a file from S3.

Parameters:

  • key: (String): S3 file key.
  • bucketName: (String): S3 bucket name.
deleteFileFromS3({
  key: '/uploads/b5c9fecc-1dd0-457f-b55d-dba223050b27',
  bucketName: 'your-bucket-name'
}).then(result => {
  console.log(result);
}).catch(error => {
  console.error(error);
});