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 build a website for uploading pictures with nodejs

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to use nodejs to build a picture upload website". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to build a picture upload website with nodejs".

The effect is as shown in the figure:

After clicking upload, the file will be placed under a uploads folder in the background. If the upload is successful, a prompt box for successful upload will pop up on the page. If the upload fails, a failed prompt box will pop up. If the network speed is slow, the progress bar during the upload process will be displayed.

Development preparation

Use the ordinary form submission method to upload files.

1. Write front-end code

Set action to submit address, enctype= "multipart/form-data"

Set the domain name of the submission form to imgfile

two。 Write code for back-end testing

Here we use the express framework. We need to install the framework first, and then use static middleware to specify the directory where our js css html files are placed.

Var app = express (); app.use (express.static ('dist'))

Download the plug-in multer that handles uploaded files

There is a basic usage in the readme.md file, so we can copy the code example and modify it a little bit. Specify the file upload path to uploads, and then name the uploaded file with the current date and file name. This imgfile domain name must strictly correspond to the front-end form file domain name.

The complete code is as follows:

"use strict"; exports.__esModule = true; var express = require ("express"); var multer = require ("multer"); var storage = multer.diskStorage ({destination: function (req, file, cb) {cb (null,'. / uploads') }, filename: function (req, file, cb) {cb (null, `${Date.now ()}-${file.originalname}`)}) var upload = multer ({storage: storage}); var app = express (); app.use (express.static ('dist')) / / var cpUpload = upload.fields ([{name: 'imgfile', maxCount: 12}]) app.post (' / uploadimg', upload.array ('imgfile', 40), function (req, res, next) {var files = req.files console.log (files) if (! files [0]) {res.send (' error');} else {res.send ('success');} console.log (files) }) var server = app.listen (9999, 'localhost', function () {console.log (' server is running at port 9999..);})

Select the file in this way, click the submit button, and the file is uploaded to the server uploads folder.

Using H5 and ajax technology to upload files without refresh

1. Modify the original Select File button to make it a cute little icon, click and select the file.

This is too simple to put the code, the specific idea is to put an a tag on the background picture, the upload file input type= "file" size to the same size as the a tag, and placed on the a tag, opacity set to 0 transparent. Clicking an is actually a click on input type= "file"

two。 Select the file to generate thumbnails, this basic idea is to listen to the input type= "file" onchange event, if the file is selected, use FileReader to generate a picture data:url to add to the div.preview inside the dynamically generated img, to div.preview set to the flex layout can flexibly place the preview.

Html

Js

Fileinput.onchange = () = > {/ / console.log ('dddd') var files = fileinput.files let imgDOMArray = new Array (files.length) let reader = [] let thumbPic = [] progressDOM = document.getElementById (' progress-img') for (let I = 0; I

< files.length; i++) { reader[i] = new FileReader() thumbPic[i] = document.createElement('div') imgDOMArray[i] = document.createElement('img') imgDOMArray[i].file = files[i] thumbPic[i].className = 'thumbPic' thumbPic[i].appendChild(imgDOMArray[i]) previewDOM.appendChild(thumbPic[i]) reader[i].readAsDataURL(files[i]) reader[i].onload = (img =>

{return e = > img.src = e.target.result}) (imgDOMArray [I])}}

3. Click the upload button to upload the picture

The basic idea is to simulate the form with Formdata, and then send the file to the server with ajax.

Var aUpload = document.querySelector ('.selectImg') var button = document.querySelector ('# upload') var fileinput = document.getElementById ('file') button.onclick = uploadFile function uploadFile () {/ / console.log (' ddd') var xhr = new XMLHttpRequest () var formdata = new FormData () var files = fileinput.files If (! files [0]) {alert ('Please select a picture first Upload again!') Return} var progress = document.querySelector ('progress') for (let I = 0; I

< files.length; i++) { formdata.append('imgfile', files[i], files[i].name) } xhr.open('POST', '/uploadimg') xhr.onload = () =>

{if (xhr.status = = 200 & & xhr.responseText = = 'success') {previewDom [XSS _ clean] =' 'xhr = null alert (' picture uploaded successfully!') }} xhr.send (formdata) xhr.upload.onprogress = e = > {if (e.lengthComputable) {var progressWrap = document.querySelector ('.progress') progressWrap.style.display = "flex" var percentComplete = e.loaded / e.total * 100 Progress.value = percentComplete if (percentComplete > = 100) {progress.value = 0 progressWrap.style.display = "none"}

The xhr.upload.onprogress is used to listen for data upload events, and the value of the H6 progress bar is dynamically set to display the upload progress. If the upload is complete, hide the progress bar.

If the server returns success, it will pop up and upload the image successfully. Otherwise, the pop-up failed to upload the picture.

Thank you for your reading, the above is the content of "how to use nodejs to build a picture upload website". After the study of this article, I believe you have a deeper understanding of how to use nodejs to build a picture upload website. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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