一,只有在上傳文件之前的鈎子函數中才可以獲得最初的文件(文件本身的二進制形式),用以以上傳服務器。
還需要使用formdata來承載數據,便於接收
<template>
<div>
<el-upload
action="http://localhost:3000/picture"
:http-request = "upload"
:before-upload = "beforeUp"
:headers="headers"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-progress="progress"
:on-remove="handleRemove">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<el-row>
<el-button type="info" plain @click="getimages">信息按鈕</el-button>
</el-row>
</div>
</template>
<script>
export default {
data() {
return {
dialogImageUrl: '',
dialogVisible: false,
headers:{},
imgArr:[]
};
},
methods: {
beforeUp(file){
console.log(file);
var formData = new FormData();
formData.append('file',file);
this.$http.post('/picture',formData)
},
handleRemove(file, fileList) {
/* 移除 */
console.log(file, fileList);
},
handlePictureCardPreview(file) {
/* 預覽 */
this.dialogImageUrl = file.url;
this.dialogVisible = true;
console.log(file);
this.$http.post('/picture',file)
},
progress(){
console.log('上傳中');
},
upload(res){
// this.imgArr.push(res)
// console.log(res);
// this.$http.post('/picture',res)
},
getimages(){
// console.log(this.imgArr);
// this.$http.post('/picture',this.imgArr)
}
},
created(){
// this.$http.get('/picture')
// this.headers ={Authorization : 'Bearer '+(localStorage.token || '')}
}
}
</script>
二,node.js服務器使用multer插件 接收上傳的圖片 ,multer插件需要接收二進制的文件
var multer = require('multer')
const upload = multer({ dest: 'uploads/' });
router.use(upload.single('file'));
router.post('/',upload.single('file'),async(req,res)=>{ //此刻圖片已存入服務器
console.log(req.body);
console.log(req.file);
})
如果有類似問題bug,可以留言一起研究,共同進步,哈哈 。。