Summary of file upload and download

Recently, I made a background system with many complicated functions. Among them is the upload function point. When uploading, we need to verify the uploaded file format, limit the number of uploads, customize the upload interface, drag and drop upload, delete, preview, and re-upload after deletion. Now calculate (this time to clear the cache list uploaded last time) and so on, so I will summarize this piece well, and just move it directly when I use it later.

upload function

<el-table-column
                                prop="dataUpload"
                                label="资料上传"
                                width="440"
                            >
                                <template #default="{ row }">
                                    <el-upload
                                        class="upload-demo"
                                        drag
                                        action="#"
                                        multiple
                                        :disabled="isEdittable != 'true'"
                                        :show-file-list="false"
                                        :http-request="
                                            (file) => uploadfile(file, row)
                                        "
                                        :before-upload="
                                            (file) => beforeUpload(file, row)
                                        "
                                        :limit="
                                            row.docType == 'other' ? 999 : 1
                                        "
                                        :on-exceed="exceedFile"
                                        :ref="
                                            (el) =>
                                                setRefs(
                                                    el,
                                                    row.id
                                                )
                                        "
                                    >
                                        <el-icon class="el-icon--upload"
                                            ><upload-filled
                                        /></el-icon>
                                        <div
                                            class="el-upload__text"
                                        >
                                            拖拽图片到此处,或
                                            <em>点此处选择文件</em>
                                        </div>
                                    </el-upload>
                                </template>
                            </el-table-column>
<script setup>
// 获取当前上传文件的html元素
const setRefs = (el, id) => {
    
    
    if (el) {
    
    
        if (!itemRefs.value.some((item) => item.id == id)) {
    
    
            itemRefs.value.push({
    
    
                id: id,
                el,
            });
        }
    }
};
//上传文件前校验文件类型
const beforeUpload = (file, row) => {
    
    
   // 做上传前的一些校验操作
};
// 超出限制文件数量的钩子函数
const exceedFile = () => {
    
    
    message.warning("只能上传一个文件");
};

// 上传文件处理函数
const uploadfile = async (file, row) => {
    
    
    if (file.file.size == 0) {
    
    
        return message.warning("文件内容为空,无法上传");
    }
    form.set("file", file.file);
    form.set("type", row.type);
    form.set("id", row.id);
    form.set("docType", row.docType);
    const loading = loading.service({
    
    
        fullscreen: true,
        background: "rgba(0,0,0,0.7)",
        text: "文件上传中",
    });
    try {
    
    
        const res = await API.upload(form);
        if (res.data.code === "000000") {
    
    
            row.files.push({
    
    
                name: res.data.name,
                id: res.data.id,
                nailid: res.data.nailid,
                nailid: res.data.nailid,
            });
            loading.close();
            message.success("文件上传成功");
        } else {
    
    
            message.error(res.data.message);
        }
    } catch (error) {
    
    
        loading.close();
        message.error("文件上传失败请重试");
    } finally {
    
    
        loading.close();
        if (itemRefs.value.length > 0) {
    
    
            itemRefs.value.forEach((item) => {
    
    
                if (item.id == row.recordItemId) {
    
    
                    item.el.clearFiles();
                }
            });
        }
    }
};
</script>

First of all, the ui component I use is elementPlus, so the tag name is el-upload;

1. Realize drag and drop

If you want to implement the drag and drop function, you need to add the drag attribute to the el-upload tag;

2. Realize multiple selection

If you want to realize the function of selecting multiple files when uploading, you need to add the multiple attribute to the el-upload tag;

3. The function of controlling whether it can be edited

If you want to realize whether it can be uploaded, you need to add the disabled attribute to the el-upload tag;

4. Implement custom upload operation function

If you want to implement a custom upload operation (write your own function and define the upload interface), you need to add the http-request attribute to the el-upload tag and give it the corresponding method;

5. Realize the verification operation function after uploading

If you want to verify before uploading, you need to add the before-upload attribute to the el-upload tag and give it the corresponding method;

6. The number of uploaded files is limited when uploading

If you want to limit the number of uploaded files when uploading, you need to add the limit attribute to the el-upload tag;

7. Implement the hook function executed when uploading exceeds the limit

If you want to upload the number of uploaded files beyond the limit, you need to add the on-exceed attribute to the el-upload tag and add the corresponding hook function;

8. If you want to get the element of the uploaded file, you need to add ref

If you want to get the html element of the uploaded file, you need to add the ref attribute, but because the el-upload element of the uploaded file is generated equivalent to v-for, you will get many el-upload elements. At this time, you need to have The unique id corresponds to the corresponding el-upload element one by one, so there will be an id to correspond to;

download function

For downloading, the backend returns a file stream, so the file stream needs to be processed;

// 处理下载文件的方法
function downLoadXls(res) {
    
    
    const fileNames = res.headers["content-disposition"];
    if (fileNames) {
    
    
        //解码
        const fileName = decodeURIComponent(fileNames.match(/=(.*)$/)[1]);
        // 处理返回的文件流
        const content = res.data;
        const blob = new Blob([content], {
    
    
            type: "application/octet-stream; charset=utf-8",
        });
        if ("download" in document.createElement("a")) {
    
    
            //非IE下载
            const a = document.createElement("a"); //创建一个a标签
            a.download = fileName; //指定文件名称
            a.style.display = "none"; //页面隐藏
            a.href = URL.createObjectURL(blob); // href用于下载地址
            document.body.appendChild(a); //插到页面上
            a.click(); //通过点击触发
            URL.revokeObjectURL(a.href); //释放URL 对象
            document.body.removeChild(a); //删掉a标签
        } else {
    
    
            //IE10 + 下载
            navigator.msSaveBlob(blob, fileName);
        }
    }
}

Guess you like

Origin blog.csdn.net/xiaolinlife/article/details/131910411