element-ui 中的组件 el-upload默认的行为是一张图片请求一次,在项目需求中,通常要求多张图片只向后台发送一次请求,下面的做法就可以解决这样的需求
前端
<template>
<el-upload
ref="upload"
:action="actionUrl"
:auto-upload="false"
list-type="picture-card"
:http-request="uploadFile"
:on-preview="handlePictureCardPreview"
accept="image/png, image/jpeg"
multiple
:limit="9"
>
<i class="el-icon-plus"></i>
</el-upload>
<button
type="button"
class="btn btn-primary btn-sm submit-btn"
@click="submitUpload"
>发布</button>
</template>
<script>
export default {
data() {
return {
formData: {},
}
}
methods: {
// 绑定在http-request,覆盖上传事件
uploadFile(file) {
this.formData.append("blogimg", file.file);
},
// 点击按钮触发
async submitUpload() {
this.formData = new FormData();
this.formData.append("content", this.blogData.content);
this.formData.append("token", this.token);
this.$refs.upload.submit();
const { data: res } = await this.$http.post(
this.actionUrl,
this.formData,
{
headers: { "Content-Type": "multipart/form-data" }
}
);
if (res.meta.status !== 200) {
return this.$message.error("发布失败!");
}
this.getUserBlogs();
this.blogData.content = "";
this.$refs.upload.clearFiles();
this.$message.success("发布成功!");
},
}
};
</script>
后端
后端使用的是multer中间件,用来接收前端发送过来的multipart/form-data形式的数据文章来源地址https://www.toymoban.com/news/detail-525768.html
multer.js
const multer = require("multer");
const path = require("path");
let dst = "../uploads";
let storageBlogimg = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, path.join(__dirname, dst));
},
filename: function(req, file, cb) {
let ext = file.originalname.substr(file.originalname.lastIndexOf("."));
let filename = file.fieldname + "-" + Date.now() + ext;
cb(null, filename);
},
});
exports.storeBlogimg = multer({ storage: storageBlogimg });
router.js
const store = require("../middleware/multer");
router.post(
"/api/createBlog",
store.storeBlogimg.array("blogimg"),//
blog_controller.createBlog
);
// array("blogimg")中的参数名称要和表单中的键值一样(blogimg)
// this.formData.append("blogimg", file.file);
文章来源:https://www.toymoban.com/news/detail-525768.html
到了这里,关于解决element-ui中组件【el-upload】一次性上传多张图片的问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!