国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial How to implement File uploads in Nodejs: A step by step guide

How to implement File uploads in Nodejs: A step by step guide

Jan 03, 2025 am 01:36 AM

Introduction

Hi, In this article we will see how to handle file uploads in a nodejs server and storing it with best practices. I will be using Apexx cloud as our file storage service.

Install the packages

npm i express nodemon cors multer @apexxcloud/sdk-node dotenv

Once installed, update your package.json to add the start script

"scripts":{
 "start": "nodemon index.js",
 // rest of the scripts
}

Create a index.js file in the root folder, then create a folder called src. In the src folder create the folders for controllers and routes respectively, Your folder structure should look something like this.

project-root/
│
├── index.js              # Entry point of the application
├── package.json          # Project metadata and dependencies
├── package-lock.json     # Auto-generated dependency tree
├── node_modules/         # Installed dependencies
│
└── src/
    ├── controllers/      # Contains controller files
    │   └── file.controller.js
    │
    ├── routes/           # Contains route files
    │   └── file.route.js

Setup Apexx cloud

  1. Login to Apexx cloud or create a new account here

  2. Navigate to buckets.

  3. Click on "Create bucket" and provide a unique name for your bucket.

  4. Select the desired region

  5. Review and create the bucket

  6. Navigate to Api keys

  7. Click on "Create API Key" and provide a name for your key

  8. Review and create the key

  9. Copy your secret key and store it somewhere securely.

  10. Then copy your access key as well.

Lets start writing some code

Lets start writing our controller that will handle the request in file.controller.js.

// Setup our apexx cloud sdk
const ApexxCloud = require("@apexxcloud/sdk-node");
const storage = new ApexxCloud({
  accessKey: process.env.APEXXCLOUD_ACCESS_KEY,
  secretKey: process.env.APEXXCLOUD_SECRET_KEY,
  region: process.env.APEXXCLOUD_REGION,
  bucket: process.env.APEXXCLOUD_BUCKET,
});

// Upload file function
const uploadFile = async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: "No file provided" });
    }
    const { originalname, filename, size, path, mimetype } = req.file;

    const { key, visibility } = req.query;

    const result = await storage.files.upload(req.file.buffer, {
      key: key || orginalname,
      visibility: visiblity || "public",
      contentType: mimetype,
    });

    res.status(200).json(result);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: `File upload failed: ${error.message}` });
  }
};

First we are importing @apexxcloud/sdk-node and we are creating a storage object by passing in the credentials. Then we are creating the function called uploadFile, In the function we are getting the key and visibility from req.query and file details from req.file

Then we are using the upload function from the apexx cloud sdk to upload it to apexx cloud. When uploading you can configure the visibility of the file, It can be public or private, All the files are public by default.

Now lets setup the routes in file.route.js.

const express = require("express");
const router = express.Router();
const multer = require("multer");
const { uploadFile } = require("../controllers/file.controller")

// setup multer
const upload = multer({ storage: multer.memoryStorage() });

// setup the route
router.post("/upload", upload.single("file"), uploadFile);

// export the router
module.exports = router

Then lets setup the index.js file.

const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cors = require("cors");

// load env variables
dotenv.config();

// import file route
const fileRoute = require("./src/routes/file.route");

// setup express
const app = express();

app.use(express.urlencoded({ extended: true, limit: "100mb" }));
app.use(express.json({ limit: "100mb" }));
app.use(cors());

// setup the file route
app.use(fileRoutes);

const port = 8000
app.listen(port, () => {
  console.log(`Server running at port:${port}`);
});

Open your terminal and run:

npm start, If everything went right, it should log "Server running at port:8000".

Testing the API

We'll test the API using postman.

How to implement File uploads in Nodejs: A step by step guide

Select Body, check form-data, add a key called file and set the type to file. Upload your file then click send.

You should get a response as below:

{
    "data": {
        "message": "File uploaded successfully",
        "key": "file.png",
        "location": "https://cdn.apexxcloud.com/f/ojGnBqCLkTnI/file",
        "bucket": "your-bucket-name",
        "region": "WNAM",
        "visibility": "private",
        "size": 14513,
        "content_type": "image/png"
    }
}

Indicating that the file has been uploaded. Go to your Apexx Cloud dashboard, Then go to your bucket, you shoud see the file you uploaded there.

And that's it, you have successfully implemented file uploads in nodejs and the best part is Apexx Cloud provides you with on the fly transformations and a superfast CDN for free. To know more go here, for the documentation go here.

Conclusion

This article has successfully taught you how to handle file uploads in a nodejs application using Apexx Cloud and Multer.

In the next article I will show how to use AWS S3 for file uploads, until then Signing Off - Your's FII

Never worry about file uploads: Sign up for Apexx Cloud Today, It's Free

The above is the detailed content of How to implement File uploads in Nodejs: A step by step guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

How can you reduce the payload size of a JavaScript application? How can you reduce the payload size of a JavaScript application? Jun 26, 2025 am 12:54 AM

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

See all articles