直接上代码,通过 ant design vue 上传组件提供的 beforeupload 钩子修改上传文件名

<template>
    <div>
        <a-upload :action="uploadURL" list-type="picture-card" :file-list="fileList" :before-upload="beforeUpload"
            :remove="fileRemove" @change="handleChange">

            <a-button><a-icontype="upload" />上传文件</a-button>

        </a-upload>

        <!--图片预览-->

        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">

            <img style="width:100%" :src="previewImage" alt="加载失败" />

        </a-modal>
    </div>

</template>

<script>

export default {

    data() {

        return {

            uploadURL: "图片上传地址",

            fileList: [],

            previewVisible: false,

            previewImage: '',

        }

    },

    methods: {

        beforeUpload(file) {

            console.log('上传文件之前的钩子', file)

            //返回新的文件对象以上传

            return new Promise((resolve) => {

                //修改文件名

                const newFileName = newDate().getTime() + '.' + file.name.split('.').pop();

                //创建一个新的文件对象,使用新的文件名

                const newFile = newFile([file], newFileName, {

                    type: file.type

                });

                newFile.uid = file.uid;

                resolve(newFile);

            });

        },

        handleCancel() {
            this.previewVisible = false;
        },

        fileRemove(file) {

            console.log('你点击了删除')

            this.previewImage = ''

            this.fileList = []

        },

        handleChange({ file, fileList }) {

            console.log('你点击了文件上传', file, fileList)

            if (file.status == 'error') {

                this.$message.error('图片上传失败,请稍后重试!')

            }

            if (file.status === "uploading") {

                this.previewImage = this.uploadURL + file.name;

                //或者后台返回的地址file.response

                this.previewImage = file.response

            }

            this.fileList = fileList;

        },



    }

}

</script>



<stylescoped>
    /*youcanmakeupuploadbuttonandsamplestylebyusingstylesheets*/

    .ant-upload-select-picture-cardi{

        font-size:32px;

        color:#999;

    }



    .ant-upload-select-picture-card.ant-upload-text{

        margin-top:8px;

        color:#666;

    }
</style>

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐