- 构建表单数据;更多信息,请访问 formData
- 上传文件
- 前端 - vue
-
<script setup>
import axios from 'axios'
const getFile = (e) => {
let file = e.target.files[0]
let formData = new FormData()
formData.append('image', file)
axios.post('/upload/upload/image', formData)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
}
</script>
<template>
<input type="file" name="file" @change="getFile">
</template>
- 后端 - API
-
router.post('/image', upload.single('image'), (req, res) => {
console.log(req.file, req.body);
res.send({
err: 0,
msg: 'ok',
data: req.body,
file: req.file
})
})
- 改进:增加上传进度指示
- 在axios请求中,添加配置项,使用进度回调onUploadProgress;为了更直观的观察效果,将开发者工具中网络Network速度由无限制改为快速3G或慢速3G
-
axios.post('/upload/upload/image', formData, {
onUploadProgress: (e) => {
console.log(Math.floor(e.loaded / e.total * 100) + '%');
}
})