Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the interface of uploading pictures to disk

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to realize the interface of uploading pictures to disk". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to upload pictures to disk interface"!

One: enable the Node.js service

Open a Node.js service and specify the route / upload/image to call the uploadImageHandler method after receiving the request, passing in the Request object.

Const http = require ('http'); const formidable = require (' formidable'); const fs = require ('fs'); const fsPromises = fs.promises; const path = require (' path'); const PORT = process.env.PORT | | 3000; const server = http.createServer (async (req, res) = > {if (req.url = ='/ upload/image' & & req.method.toLocaleLowerCase () = 'post') {uploadImageHandler (req, res);} else {res.setHeader (' statusCode', 404) Res.end ('Not clients')}); server.listen (PORT, () = > {console.log (`server is listening at ${server.address () .port} `);})

Second: deal with picture objects

Formidable is a NPM module used to process uploaded files, pictures and other data. Form.parse is a callback converted into Promise for easy processing.

Tips: use the join method of path module when stitching paths, which will stitch together multiple path parameters we have passed, because different systems such as Linux and Windows use different symbols, and this method will be converted according to the system itself.

Const uploadImageHandler = async (req, res) = > {const form = new formidable.IncomingForm ({multiples: true}); form.encoding = 'utf-8'; form.maxFieldsSize = 1024 * 5; form.keepExtensions = true; try {const {file} = await new Promise ((resolve, reject) = > {form.parse (req, (err, fields, file) = > {if (err) {return reject (err)) } return resolve ({fields, file}); const {name: filename, path: sourcePath} = file.img; const destPath = path.join (_ _ dirname, filename); console.log (`sourcePath: ${sourcePath}. DestPath: ${destPath} `); await mv (sourcePath, destPath); console.log (`File ${filename} write room.`); res.writeHead (200,{ 'Content-Type':' application/json'}); res.end (JSON.stringify ({code: 'SUCCESS', message: `Upload room.`);} catch (err) {console.error (`Move file failed with message: ${err.message}`) Res.writeHead (200,{ 'Content-Type':' application/json'}); res.end (JSON.stringify ({code: 'ERROR', message: `${err.message}`));}}

Third, implement the mv method

Fs.rename renames the file

A simple way to write the uploaded image to the local destination path is to use the rename (sourcePath, destPath) method of the fs module, which asynchronously renames the sourcePath file as follows:

Const mv = async (sourcePath, destPath) = > {return fsPromises.rename (sourcePath, destPath);}

Cross-device link not permitted

Also pay attention to cross-device link not permitted errors when using fs.rename (), see rename (2)-Linux manual page:

* EXDEV * * oldpath and newpath are not on the same mounted filesystem. (Linux permits a filesystem to be mounted at multiple points, but rename () does not work across different mount points, even if the same filesystem is mounted on both.)

OldPath and newPath are not on the same mounted file system. (Linux allows a file system to be mounted to multiple points, but rename () cannot work across different mount points, even if the same file system is mounted on two mount points.)

You will also encounter this problem on Windows systems, refer to http://errorco.de/win32/winerror-h/error_not_same_device/0x80070011/

Winerror.h 0x80070011 # define ERROR_NOT_SAME_DEVICE The system cannot move the file to a different disk drive. (the system cannot move files to a different disk drive.)

This is done in Windows, because the default directory when uploading files using formidable is the default directory of the operating system, os.tmpdir (). On my computer, when I use fs.rename () to rename it to disk F, the following error occurs:

C:\ Users\ ADMINI~1\ AppData\ Local\ Temp\ upload_3cc33e9403930347b89ea47e4045b940 F:\ study\ test\ 202366 [Error: EXDEV: cross-device link not permitted, rename' C:\ Users\ ADMINI~1\ AppData\ Local\ Temp\ upload_3cc33e9403930347b89ea47e4045b940'->'F:\ study\ test\ 202366'] {errno:-4037, code: 'EXDEV', syscall:' rename', path: C:\\ Users\\ ADMINI~1\\ AppData\\ Local\\ Temp\\ upload_3cc33e9403930347b89ea47e4045b940' Dest:'F:\\ study\\ test\\ 202366'}

Set the source path and destination path to the same disk partition

Set the temporary path of the upload file middleware to the disk partition where the file is finally written. For example, we saved the image under disk F during the Windows test, so set the uploadDir property of the form object of formidable to disk F, as shown below:

Const form = new formidable.IncomingForm ({multiples: true}); form.uploadDir ='F:\\ 'form.parse (req, (err, fields, file) = > {...})

This approach has some limitations, what if the location of the write is on a different disk space?

You can take a look at this way.

Read-write-delete temporary files

One possible way is to read the temporary file and write it to a new location, and finally delete the temporary file. So the following code creates a readable stream and a writeable stream object, writes the data to a new location in a pipeline way using pipe, and finally calls the unlink method of the fs module to delete the temporary file.

Const mv = async (sourcePath, destPath) = > {try {await fsPromises.rename (sourcePath, destPath);} catch (error) {if (error.code = 'EXDEV') {const readStream = fs.createReadStream (sourcePath); const writeStream = fs.createWriteStream (destPath); return new Promise (resolve, reject) = > {readStream.pipe (writeStream); readStream.on (' end', onClose); readStream.on ('error', onError) Async function onClose () {await fsPromises.unlink (sourcePath); resolve ();} function onError (err) {console.error (`File write failed with message: ${err.message} `); writeStream.close (); reject (err)})} throw error;}}

Four: testing

Method 1: terminal call

Curl-location-request POST 'localhost:3000/upload/image'\-form' img=@/Users/Downloads/ May Jun.jpeg'

Method 2: POSTMAN call

At this point, I believe you have a deeper understanding of "how to upload pictures to disk interface". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report