VUE3+ElementPlus如何实现文件上传
VUE3+ElementPlus如何实现文件上传
·
VUE3+ElementPlus如何实现文件上传
使用elementplus 中的组件 el-upload
以上传单张图片为例:
使用el-upload
<el-upload
ref="uploadFile"
action='#'
:http-request="uploadAction"
:on-exceed="handleExceed"
:limit="1"
:show-file-list="false"
:auto-upload="true"
:before-upload="beforeUpload" style="width: 100%;" class="left-view">
<img v-if="bannerUrl" :src="bannerUrl" class="avatar" />
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
ts实现
<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from 'vue';
import type { UploadRawFile, UploadFile, FormInstance, Action } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { uploadImage } from '../../apis/project';
export default defineComponent({
name: 'BanaerManage',
components: {},
setup() {
const uploadFile = ref();
const state = reactive({
bannerUrl: '',
fileList: [],
fileName: '',
})
const handleExceed = (files: File[], fileList: UploadFile[]) => {
if (state.fileList.length >= 1) {
ElMessage.error('只能上传一个图片')
return;
}
}
const beforeUpload = (file: UploadRawFile) => {
const type = ['image/jpeg', 'image/jpg', 'image/png']
if (type.indexOf(file.type) === -1) {
ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!')
return false
} else if (file.size / 1024 / 1024 > 2) {
ElMessage.error('图片大小不能超过2MB!')
return false
}
return true
}
const uploadAction = (option: any) => {
let param = new FormData();
param.append('file', option.file);
uploadImage(param).then((res: any) => {
if (res && res.code === 0) {
state.fileName = res.data.fileName;
state.bannerUrl = res.data.imageUrl;
ElMessage.success('图片上传成功!');
} else {
if (res && res.msg) {
ElMessage.error(res.msg);
} else {
ElMessage.error('图片上传失败!');
}
}
})
}
return {
...toRefs(),
uploadFile,
uploadAction,
beforeUpload,
handleExceed
}
}
})
简单实现场景,服务端我是用nodejs实现的,后面给大家更新一下nodejs+koa2实现如何接收文件
谢谢
更多推荐
已为社区贡献1条内容
所有评论(0)