Nodejs sample code for image preview and upload

黄舟
Release: 2017-10-01 07:42:51
Original
1898 people have browsed it

This article mainly introduces the sample code for nodejs image preview and upload. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

This article introduces the sample code for nodejs image preview and upload, and shares it with everyone. The details are as follows:

The effect is as follows:

Preface

Generally, you need to temporarily preview the image locally before uploading it.

The front-end image preview uses the readAsDataURL method of FileReader

nodejs image upload uses the middleware Multer

Local Image Preview

The FileReader object allows a web application to asynchronously read the contents of a file (or raw data buffer) stored on the user's computer, using a File or Blob object to specify the file to read or data.

The readAsDataURL method is used to read the contents of the specified Blob or file. When the read operation is completed, readyState is completed and loadend is triggered. At that point, the result attribute contains the data as a URL representing the file, as a base64-encoded string.

Single image preview

html part



Image preview...
Copy after login

javascript part


function previewFile() { var preview = document.querySelector('img'); var file = document.querySelector('input[type=file]').files[0]; var reader = new FileReader(); reader.addEventListener("load", function () { preview.src = reader.result; }, false); if (file) { reader.readAsDataURL(file); } }
Copy after login

Multiple picture preview

html part


 

Copy after login

javascript part


function previewFiles() { var preview = document.querySelector('#preview'); var files = document.querySelector('input[type=file]').files; function readAndPreview(file) { // 支持的图片类型(可自定义) if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { var reader = new FileReader(); reader.addEventListener("load", function () { var image = new Image(); image.height = 100; image.title = file.name; image.src = this.result; preview.appendChild( image ); }, false); reader.readAsDataURL(file); } } //files 就是input选中的文件,你也可以对上传图片个数进行限制 (files.length) if (files) { [].forEach.call(files, readAndPreview); } }
Copy after login

Used in the project

Front-end part

html


  

Copy after login

javascript

js The method part is broken down and it is a bit long to put it in one code block (please check the context when reading)


$(function(){ var upload={ txtUploadFile:$('#txtUploadFile'), //上传单个文件 txtUploadFileList:$('#txtUploadFileList'), //上传多个文件 btnSend:$('#btnSend'), //上传文件 preview:$('#preview'),//图片预览盒子 //预览图片加载 previewImgLoad:function(fileList){ for(var i=0;i
        
Copy after login


/* 上传单个文件 这里是input改变时后直接上传(用于修改用户头像) 你也可以在点击上传按钮后再上传,下面的多图上传会给出案例 */ upload.txtUploadFile.change(function(){ var formData = new FormData(); formData.append('avatar',upload.txtUploadFile[0].files[0]); $.ajax({ url: '/upload/file', type: 'post', cache: false, data: formData, processData: false, contentType: false, success:function(res){ console.log('upload success'); }, error:function(){ console.log('upload faild'); } }); });
Copy after login


//加载预览图片 upload.txtUploadFileList.change(function(){ var fileList=this.files; upload.previewImgLoad(fileList); });
Copy after login


//上传多张图片 upload.btnSend.click(function(){ var files = upload.txtUploadFileList.prop('files'); if(files.length==0){ //没有选择文件直接返回 return; } var formData=new FormData(); for(var i=0;i
        
Copy after login

nodejs part

nodejs uses Multer Middleware, this middleware is mainly used to upload files

Install Multer


npm install --save multer
Copy after login

Multer is used in nodejs


var express = require('express'); var multer = require('multer'); var app = express(); //磁盘存储引擎(说白了就是指定上传的文件存储到哪,当然你也可以对文件重命名等等) var storage=multer.diskStorage({ destination: function (req, file, cb) { //我这里是存储在public下的uploads目录 cb(null, 'public/uploads/') }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now()+"_" + file.originalname) } });
Copy after login

Single picture upload


//如果图片上传成功会返回图片的存储路径 app.post('/upload/file', upload.single('avatar'), function(req, res) { if (!req.file) { console.log("no file received"); return res.send({ status: 0, filePath:'' }); } else { console.log('file received'); res.send({ status:1, filePath: '/uploads/' + path.basename(req.file.path) }); } });
Copy after login

Multiple picture upload


// 如果图片上传成功会返回图片的存储路径(数组) app.post('/upload/filesList', upload.array('photos',9), function(req, res) { if (req.files==undefined) { console.log("no files received"); return res.send({ status: 0, filePath:'' }); } else { var filesPathArr=[]; for(var i=0;i
        
Copy after login

The above is the detailed content of Nodejs sample code for image preview and upload. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!