使用node.js怎么实现多文件上传?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
// 前端 upload.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>上传文件demo</title>
<style media="screen">
.progress{
width: 50%;
height: 5px;
border: 1px solid #ccc;
border-radius: 4px;
margin-top: 10px;
position: relative;
}
.progress>span{
display: inline-block;
position: absolute;
border-radius: 4px;
top: 0;
left: 0;
height: 100%;
width: 0;
background-color: rgb(98, 230, 74);
transition: width 0.3s ease-out;
}
</style>
</head>
<body>
<input id="file" type="file" multiple>
<div class="progress">
<span></span>
</div>
<script type="text/javascript">
var http = function (option) {
// 过滤请求成功后的响应对象
function getBody (xhr) {
var text = xhr.responseText || xhr.response
if (!text) {
return text
}
try {
return JSON.parse(text)
} catch (err) {
return text
}
}
var xhr = new XMLHttpRequest();
// 自定义 beforeSend 函数
if(option.beforeSend instanceof Function) {
if (option.beforeSend(xhr) === false) {
return false
}
}
xhr.onreadystatechange = function () {
if (xhr.status === 200) {
if (xhr.readyState === 4) {
// 成功回调
option.onSuccess(getBody(xhr))
}
}
}
// 请求失败
xhr.onerror = function (err) {
option.onError(err)
}
xhr.open(option.type, option.url, true)
// 当请求为上传文件时回调上传进度
if (xhr.upload) {
xhr.upload.onprogress = function (event) {
if (event.total > 0) {
event.percent = event.loaded / event.total * 100;
}
// 监控上传进度回调
if (option.onProgress instanceof Function) {
option.onProgress(event)
}
}
}
// 自定义头部
const headers = option.headers || {}
for (var item in headers) {
xhr.setRequestHeader(item, headers[item])
}
xhr.send(option.data)
}
// 测试接口
http({
type: 'POST',
url: '/test',
data: JSON.stringify({
name: 'yolo'
}),
onSuccess: function (data) {
console.log(data)
},
onError: function (err) {
console.log(err)
}
})
document.getElementById('file').onchange = function () {
var fileList = this.files, formData = new FormData();
Array.prototype.forEach.call(fileList, function (file) {
formData.append(file.name, file)
})
// 当上传的数据为 file 类型时,请求的格式类型自动会变为 multipart/form-data, 如果头部格式有特定需求,在我的 http 函数中传入 headers<Object> 即可,大家可自己查看,我这里没有什么特殊处理所以就不传了
http({
type: 'POST',
url: '/upload',
data: formData,
onProgress: function (event) {
console.log(event.percent)
document.querySelector('.progress span').style.width = event.percent + '%';
},
onSuccess: function (data) {
console.log('上传成功')
},
onError: function (err) {
alert(err)
}
})
}
</script>
</body>
</html>
后端所用的一些东西我放在这
express中间件-multer
express 4.x 文档
// 后端(node.js) upload.js
var express = require('express');
var path = require('path');
var fs = require('fs');
var app = express();
var bodyParser = require('body-parser'); // 过滤请求头部相应格式的body
var multer = require('multer');
var chalk = require('chalk'); // 只是一个 cli 界面字体颜色包而已
var log = console.log.bind(console);
app.use(express.static('static'));
// 接受 application/json 格式的过滤器
var jsonParser = bodyParser.json()
// 接受 application/x-www-form-urlencoded 格式的过滤器
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// 接受 text/html 格式的过滤器
var textParser = bodyParser.text()
// 自定义 multer 的 diskStorage 的存储目录与文件名
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'view')
},
filename: function (req, file, cb) {
cb(null, file.fieldname)
}
})
var upload = multer({ storage: storage })
// 页面渲染
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'view/upload.html'));
})
app.post('/test', textParser, jsonParser, function (req, res) {
log(req.body);
var httpInfo = http.address();
res.send({
host: httpInfo.address,
port: httpInfo.port
})
})
// 对应前端的上传接口 http://127.0.0.1:3000/upload, upload.any() 过滤时不对文件列表格式做任何特殊处理
app.post('/upload', upload.any(), function (req, res) {
log(req.files)
res.send({message: '上传成功'})
})
// 监控 web 服务
var http = app.listen(3000, '127.0.0.1', function () {
var httpInfo = http.address();
log(`创建服务${chalk.green(httpInfo.address)}:${chalk.yellow(httpInfo.port)}成功`)
})
关于使用node.js怎么实现多文件上传问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。