在vue中如何上传图片呢?如何使用ajax/axios上传图片?,其实很简单,废话不多说,直接上代码,前端
<template>
<div>
<!--点击选择图片-->
<input @change="fileChange($event.target)" type="file" id="upload_file" accept="image/*" multiple />
<div>
<!--遍历显示已选择的图片-->
<img style="width:30%;margin-left: 3%;" v-for="(item,index) of imgList" :src="item.src">
</div>
<button @click="submit"></button>
</div>
</template>
<script>
import qs from 'qs';
import axios from 'axios';
export default {
name: 'upload',
data() {
return {
imgList:[],
limitSize:30*1024*1024 //单位B,上传限制30M
}
},
mounted: function () {
},
computed: {},
methods: {
/**
* @Description: 文件改变时读取images
* @param: fileList
* @return: imageList
*/
fileList(fileList) {
const vm = this;
const files = fileList.files;
//图片最多只能上传3张
if (this.imgList.length + fileList.files.length > 3) {
return alert('最多只能上传3张图片');
}
//判断已选择图片的大小
let imageSize = 0;
for (let i = 0; i < files.length; i++) {
imageSize += files[i].size;
}
if(imageSize > this.limitSize){
return alert(`图片上传限制(${this.limitSize}M)`);
}
//遍历读取已选择的图片,base64格式
for (let i = 0; i < files.length; i++) {
// reader.readAsDataURL(files[i]);
const reader = new FileReader();
reader.readAsDataURL(files[i])
reader.onload = function () {
vm.imgList.push({
src: this.result
});
};
}
},
/**
* @Description: 使用axios上传images
* @param: this.imageList
* @return: success or error
*/
submit(){
axios({
method: 'post',
url: './api/common/uploadShops',
data: qs.stringify({imageList: this.imgList})
}).then(response => {
})
}
},
activated: function () {
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
后端使用express框架,需加入一点代码:
express4.0之前:
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
之后:
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
接收就很简单了直接从req.body中读取imageList就可以了
const express = require('express');
const router = express.Router();
router.post('/upload', upload);
function upload(req, res, next) {
const imageList = req.body.imageList;
//todo...
res.end('success');
}
module.exports = router;
感谢您的阅读!如果文章中有任何错误,或者您有更好的理解和建议,欢迎和我联系!