普通文件上传
const express = require('express');
const app = express();
const path = require('path')
const multiparty = require('multiparty'); // 处理上传文件
app.use(express.static(path.join(__dirname, 'public')))
// 普通文件上传
app.post('/sendfile', (req, res) => {
// 上传到temp地址
const form = new multiparty.Form();
form.encoding = 'utf-8';
// 需要有file文件夹,否则报错
form.uploadDir = 'file'
form.parse(req, function (err, fields, files) {
// 处理其他
})
form.on('file', () => {
res.send('ok');
})
})
app.listen(2000)
<input type="file" id="file">
<button onclick="sendFile()">上传</button>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>
// 文件
let file = null;
document.getElementById('file').addEventListener('change', e => {
file = e.target.files[0]
})
// 普通文件上传
function sendFile() {
const formData = new FormData();
formData.append('file', file);
sendFileApi(formData)
}
// 文件上传api
function sendFileApi(data) {
axios({
url: "http://localhost:2000/sendfile",
method: "POST",
data
})
.then((result) => {
console.log(result)
}).catch((err) => {
console.log(err);
});
}