上传的组件,就用到了写上

本文介绍了在Vue.js中实现上传组件的功能,包括上传多个文件、限制文件个数(最大10个)和大小(10MB),当任一文件超出大小则全部上传失败。此外,还涉及到单次调用接口上传文件、预览和下载功能,以及通过fileType限制上传文件类型。在使用时,通过showType控制上传或预览按钮的显示,并提供了deleteAttachment方法用于删除附件,以及udpChange方法用于触发上传操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上传功能,上传多个,限制个数,大小10MB

  1. 多选,选多个后有一个超出10MB就全部失败。
  2. 调用一次接口,上传个文件
  3. 预览和下载
    点击上传的按钮
    多选
    多选之后支持预览下载和删除
    预览
// main.js里面全局引用了下这个ElImageViewer 的预览还将上传的做成全局的组件,别的区域应用就不用一直import了
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import AttachmentView from '@/components/attachment-view/attachment_view';
Vue.component('ElImageViewer', ElImageViewer);
Vue.component('AttachmentView', AttachmentView);
Vue.use(ElImageViewer);
Vue.use(AttachmentView);

fileType:限制了上传文件的类型

<template>
    <div>
        <div v-show="attachmentList && attachmentList.length > 0" v-for="(item, index) in attachmentList" :key="item.attachmentUrl">
            <el-dropdown  size="mini" @command="(val) => {handleCommand(val, item, index)}">
                <span class="el-dropdown-link">
                    <span class="tx_blue cur_pointer tx_14">
                        {{item.attachmentName}}
                    </span>
                </span>
                <el-dropdown-menu slot="dropdown" style="top: 250px;left: 285px;">
                    <el-dropdown-item @click="perView(item)" command="perView" v-if="getShow(item)">预览</el-dropdown-item>
                    <el-dropdown-item @click="downLoad(item)" command="downLoad">下载</el-dropdown-item>
                    <el-dropdown-item v-if="$route.params.type !== 'details' && $route.params.type !== 'SP' && $route.params.type !== 'sp'" @click="deleteAttachment(item)" command="deleteAttachment">
                        删除
                    </el-dropdown-item>
                </el-dropdown-menu>
                <!--  -->
            </el-dropdown>
            <el-divider direction="vertical"></el-divider>
        </div>
        <ElImageViewer
            v-if="showViewer"
            :on-close="showViewerClose"
            :url-list="[perViewUrl]">
        </ElImageViewer>
        <el-button style="color:#169BD5" @click="updClick" v-if="showType" size="mini">点击上传附件</el-button>
        <input id="file" ref="fileUpdload" @change='handleFileChange' type="file"  name="file" multiple="multiple" v-show="false"  accept=".jpg,.jpeg,.png,.JPG,.JPEG,.pdf,.PDF,.xlsx,.xls,.doc,.docx"/>
    </div>
</template>
<script>
import mixinList from '@/mixins/list';
export default {
    name: 'attachment_view',
    mixins: [mixinList],
    props: {
        attachmentList: {
            type: Array,
            default: () => null
        },
        showType: {
            type: Boolean,
            default: false
        },
        maxNum: {
            type: Number,
            default: 10
        }
    },
    data () {
        return {
            loading: false,
            perViewUrl: '',
            showViewer: false,
            fileList: [],
            updloadFileList: [],
            errorList: [],
            fileType: ["application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 'image/jpeg', "image/png", "application/pdf"]
        };
    },
    created () {
    },
    mounted () {
    },
    methods: {
        perView (item) {
            let fix = item.attachmentName.substring(item.attachmentName.lastIndexOf('.')+1);
            let image = ['JPG','PNG','jpg','png'];
            if (image.indexOf(fix) <= -1) {
                this.$message({
                    type: 'error',
                    message: '抱歉此类文件暂时不支持预览,请下载',
                    duration: 2000
                });
                return ;
            }
            this.perViewUrl = item.attachmentUrl;
            this.showViewer = true;
        },
        showViewerClose () {
            this.showViewer = false;
        },
        // 附件下拉选择
        handleCommand (val,item, index) {
            console.log(val,item);
            if (val == 'perView') {
                this.perView(item);
            }
            if (val == 'downLoad') {
                if (!item.attachmentUrl) return false;
            	window.open(item.attachmentUrl, '_blank');
            }
            if (val == 'deleteAttachment') {
                this.$emit('deleteAttachment', index);
            }
        },
        updClick () {
            this.$refs.fileUpdload.value=null;
            this.$refs.fileUpdload.click();
        },
        handleFileChange (file) {
            let filesList = file?.target?.files;
            let attachmentList = this.attachmentList ? this.attachmentList : [];
            if (filesList.length + attachmentList.length > this.maxNum) {
                this.$message({
                    type: 'error',
                    message: `最多上传10个附件,请重新选择上传的文件`,
                    duration: 3000
                });
                return false;
            }
            for (let i = 0; i < filesList.length; i++) {
                let fileItem = filesList[i];
                if (this.fileType.indexOf(fileItem.type) <= -1) {
                    this.$message({
                        type: 'error',
                        message: '只能上传word,excel,pdf,jpg,png类型的文件,请重新上传!'
                    });
                    return false;
                }
                // 1024*1024*10
                if (fileItem.size > 10485760) {
                    this.$message({
                        type: 'error',
                        message: '文件不能大于10MB,请重新上传!'
                    });
                    return false;
                }
            }
            this.$emit('udpChange', filesList);
        },
        getShow (item) {
            let flag = false;
            if (item.attachmentName.indexOf('JPG') >= 0) flag = true;
            if (item.attachmentName.indexOf('jpg') >= 0) flag = true;
            if (item.attachmentName.indexOf('PNG') >= 0) flag = true;
            if (item.attachmentName.indexOf('png') >= 0) flag = true;
            return flag;
        }
    }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dropdown{
    line-height: 10px;
}
</style>

上传的js

udpChange(file, fileList) {
			// 传过来的file是个数组,放到表单里去
            let formData = new FormData();
            for (let i = 0; i < file.length; i++) {
                formData.append("file", file[i]);
            }
            let that = this;
            this.$serviceApi.fileUploadFiles(formData).then(res => {
                if (res.code == '0') {
                    let params = res.data;
                    that.subForm.sysBaseAttachmentPOs = that.subForm.sysBaseAttachmentPOs ? that.subForm.sysBaseAttachmentPOs : [];
                    that.subForm.sysBaseAttachmentPOs.push(...params);
                    that.$forceUpdate();
                }
                that.$message({
                    message: res.message,
                    type: res.code == '0'? "success" : 'error'
                });
            }).catch(() => {
            });
        },

使用的地方:

  1. showType = true 表示显示上传按钮,不显示上传按钮的时候就是预览的时候.
  2. maxNum=10 表示最大上传的数
  3. deleteAttachment:删除某一个附件的方法
  4. udpChange:上传的接口和方法
<AttachmentView :attachmentList='attachments' @deleteAttachment='deleteAttachment'  @udpChange='udpChange' :showType='true' maxNum='10'></AttachmentView>

粗糙的记录一下的时候是后台就提供了一个url用浏览器的那个下载不支持txt来着。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值