> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# el-upload 上传封装

## 需求场景

借助 iViewUI 来介绍的自定义 Upload 文件上传，上次是一个组件中只使用了一次文件上传。后续走后台管理系统时，又有了新的需求，同一个组件中有多个地方要用到文件上传，为了简化代码，优化代码逻辑结构，最后尝试了修改上传组件官方提供的属性值和相应的钩子函数，最终实现了同一组件中多次使用 Upload 文件上传。

## 代码逻辑（其余事件函数请参考 iview 文件上传）

```html title="代码示例"
<el-form-item label="上传附件">
    <input type="hidden" v-model.trim="popForm.path" />
    <!-- 上传文件 -->
    <el-upload
        :disabled="loading"
        :action="upAction"
        :data="upData"
        :file-list="fileList"
        :before-upload="beforeUpload"
        :on-error="onError"
        :on-success="(res, file) => onSuccess(res, file, 'popForm')"
        :on-remove="file => onRemove(file, 'popForm')"
    >
        <el-button
            size="small"
            type="primary"
            icon="el-icon-upload el-icon--right"
            :loading="loading"
        >
            上传附件
        </el-button>
    </el-upload>
</el-form-item>
```

## JS 代码

```javascript title="代码示例"
/* 上传文件 */
beforeUpload(file) {
    /* 0：文档文件（doc、docx、ppt、pptx）、1：视频文件（mp4）、2：压缩文件（zip、rar） */
    let fileName = fileRename(String(file.name)); /* 文件重命名 */
    let { accessKeyId, policy, signature, filePath } = oss;
    Object.assign(this.upData, {
        key: filePath[0] + fileName,
        policy: policy,
        OSSAccessKeyId: accessKeyId,
        signature: signature,
        name: fileName
    });
    this.loading = true;
},
/* 上传成功回调 */
onSuccess(res, file, formName) {
    this.loading = false;
    let fileURI = this.upAction + "/" + this.upData.key;

    if (formName === "popForm") {
        this.popForm.filePath = fileURI;
    } else if (formName === "upForm") {
        this.upForm.url = fileURI;
    }
    this.$message.success("文件上传成功");
},
/* 移除文件 */
onRemove(file, formName) {
    if (formName === "popForm") {
        this.popForm.filePath = "";
    } else if (formName === "upForm") {
        this.upForm.url = "";
    }
    this.$message.success("附件移除成功");
},
/* 上传失败 */
onError(err, file) {
    this.loading = false;
    this.$message.error("文件上传失败，请稍后再试！");
},
```

:::tip 提示
代码都是写在 vue methods 函数中的，请参考上篇文章 [iView OSS 直传](/blog/upload/oss-direct-upload.md) 做修改。方法类似，此处做了微调。
:::
