上传图片
Posted jjmirai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传图片相关的知识,希望对你有一定的参考价值。
html
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <input type="file" name="file" id="file" /> <button id="upload">上传</button> <span id="progress">0</span> <img id="image" src="" width="200" /> </body> </html> <script type="text/javascript" src="./index.js"></script>
1、前台
(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]); } })();
2、后台
const express = require(‘express‘); const upload = require(‘multer‘)({ dest: ‘uploads/‘ }); const path = require(‘path‘); const fs = require(‘fs‘); const port = 3000; 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); });
以上是关于上传图片的主要内容,如果未能解决你的问题,请参考以下文章