Home  >  Article  >  Web Front-end  >  How to write the root path of nodejs image upload

How to write the root path of nodejs image upload

PHPz
PHPzOriginal
2023-04-05 10:29:27630browse

With the popularity of mobile Internet and Web applications, pictures, as an important carrier for information transmission, are widely used in various application scenarios, and their upload and display are a common requirement. In web development, Node.js, as a lightweight server-side running environment, provides a fast and efficient development method. This article will introduce image uploading and root path configuration in Node.js.

1. Node.js image upload

To implement image upload in Node.js, you can use the third-party module Express-fileupload. It is very convenient to use this module. You only need to install and reference the module. Then configure it accordingly in the code.

Install the Express-fileupload module:

npm install --save express-fileupload

Then reference the module in the code:

const fileUpload = require('express-fileupload');

Use the module and configure the upload path, limit size, etc.:

app.use(fileUpload({
    limits: { fileSize: 50 * 1024 * 1024 }, //限制文件大小
    useTempFiles: true,
    tempFileDir: '/tmp/',
    uploadTimeout: 120000, //上传时间
    abortOnLimit:true,
    createParentPath:true //创建父级路径
}));

In the above code, limits limits the maximum size of uploaded files to 50MB, useTempFiles means using temporary folders to store uploaded files, tempFileDir means specifying temporary files folder path, uploadTimeout represents the upload time, abortOnLimit represents whether to terminate the upload when the file size limit is exceeded, createParentPath represents whether to create a parent path.

Process the upload request in the route, use the moveTo method to move the uploaded file to the specified directory to complete the file upload operation.

app.post('/upload', (req, res) => {
    if (!req.files) {
        return res.status(400).send('No files were uploaded.'); //上传失败返回错误提示
    }

    const file = req.files.file; //获取文件对象

    file.mv('/path/to/upload/folder/' + file.name, (err) => { //将文件移动到指定的目录并重新命名
        if (err) {
            return res.status(500).send(err);
        }

        res.send('File uploaded!');
    });
});

In the above code, the file object represents the uploaded file. Use the mv method to move the file to the specified directory and rename the file.

2. Node.js root path configuration

In Node.js, you can use the global variable __dirname to obtain the full path of the directory where the currently executing script is located. This is generally used. The variable serves as the root path, and you can use path splicing to write relative paths when processing files.

For example, when configuring a static file directory in the Express framework, the root path is usually used as the prefix of the static file directory to avoid path errors.

app.use(express.static(__dirname + '/public'));

In the above code, the directory of the public file is public. Use __dirname to splice the relative path of the directory to ensure that the correct reading is done when the application starts. path.

3. How to write the root path of Node.js image upload

When implementing Node.js image upload, you usually need to specify the storage path of the uploaded image. To avoid path errors, you can use the root path plus relative path for path splicing.

For example, to configure the image upload path to the uploads folder under the root path, you can write the following code:

const UPLOAD_PATH = __dirname + '/uploads';

file.mv(UPLOAD_PATH + '/' + file.name, (err) => {
    if (err) {
        return res.status(500).send(err);
    }

    res.send('File uploaded!');
});

In the above code, UPLOAD_PATH Indicates the uploaded image storage path, which is spliced ​​using the root path plus relative path to achieve correct path splicing.

Summary

Image uploading and root path configuration are both very important in the development of Node.js. Correct configuration and implementation can reduce path errors and upload failures during development. question. This article introduces the steps to use the Express-fileupload module to implement image upload, and explains how to correctly configure the root path in Node.js. I wish readers can successfully use it in actual development.

The above is the detailed content of How to write the root path of nodejs image upload. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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