Ajax异步文件上传与NodeJS express服务端处理(2)

(function () { 'use strict'; var file = document.querySelector('#file'); var upload = document.querySelector('#upload'); var progress = document.querySelector('#progress'); var image = document.querySelector('#image'); var xhr = new XMLHttpRequest(); upload.addEventListener('click', uploadFile, false); file.addEventListener('change', previewImage, false); // 点击上传 function uploadFile(event) { var formData = new FormData(); formData.append('test-upload', file.files[0]); xhr.onload = uploadSuccess; xhr.upload.onprogress = setProgress; xhr.open('post', '/upload', true); xhr.send(formData); } // 成功上传 function uploadSuccess(event) { if (xhr.readyState === 4) { console.log(xhr.responseText); } } // 进度条 function setProgress(event) { if (event.lengthComputable) { var complete = Number.parseInt(event.loaded / event.total * 100); progress.innerHTML = complete + '%'; } } // 图片预览 function previewImage(event) { var reader = new FileReader(); reader.onload = function (event) { image.src = event.target.result; }; reader.readAsDataURL(event.target.files[0]); } })();

express服务器提供文件上传接口

const express = require('express'); const upload = require('multer')({ dest: 'uploads/' }); const path = require('path'); const fs = require('fs'); const port = 8080; let app = express(); app.set('port', port); // index.html, index.js放在static文件夹中 app.use(express.static(path.join(__dirname, 'static'))); app.get('*', (req, res) => { res.redirect('index.html'); }); app.post('/upload', upload.single('test-upload'), (req, res) => { // 没有附带文件 if (!req.file) { res.json({ ok: false }); return; } // 输出文件信息 console.log('===================================================='); console.log('fieldname: ' + req.file.fieldname); console.log('originalname: ' + req.file.originalname); console.log('encoding: ' + req.file.encoding); console.log('mimetype: ' + req.file.mimetype); console.log('size: ' + (req.file.size / 1024).toFixed(2) + 'KB'); console.log('destination: ' + req.file.destination); console.log('filename: ' + req.file.filename); console.log('path: ' + req.file.path); // 重命名文件 let oldPath = path.join(__dirname, req.file.path); let newPath = path.join(__dirname, 'uploads/' + req.file.originalname); fs.rename(oldPath, newPath, (err) => { if (err) { res.json({ ok: false }); console.log(err); } else { res.json({ ok: true }); } }); }); app.listen(port, () => { console.log("[Server] localhost:" + port); });

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwydxw.html