vue中实现文件的上传

1.封装上传的axios请求

import axios from 'axios'

export const http = {
    get: (url, params = {}) => {
        let pname = window.location.pathname.split("/")[1]
        if (process.env.NODE_ENV == "production") {
            url = '/' + pname + url
        }else{
            url = '/DreamWeb' + url
        }
        return new Promise((resolve, reject) => {
            axios({
                method: 'get',
                url: url,
                dataType: "json",
                crossDomain: true,
                cache: false,
                data: params
            }).then(res => {
                resolve(res)
            }).catch(error => {
                reject(error)
            })
        })
    },
    post: (url, params = {}) => {
        let pname = window.location.pathname.split("/")[1]
        if (process.env.NODE_ENV == "production") {
            url = '/' + pname + url
        }else{
            url = '/DreamWeb' + url
        }
        return new Promise((resolve, reject) => {
            axios({
                method: 'post',
                url: url,
                dataType: "json",
                crossDomain: true,
                cache: false,
                data: params
            }).then(res => {
                resolve(res)
            }).catch(error => {
                reject(error)
            })
        })
    },
    upload: (url, formData) => {
        let pname = window.location.pathname.split("/")[1]
        if (process.env.NODE_ENV == "production") {
            url = '/' + pname + url
        }else{
            url = '/DreamWeb' + url
        }
        return new Promise((resolve, reject) => {
            axios({
                method: 'post',
                url: url,
                dataType: "json",
                crossDomain: true,
                cache: false,
                headers: {
                    'Content-type': 'multipart/form-data'
                },
                data: formData
            }).then(res => {
                resolve(res)
            }).catch(error => {
                reject(error)
            })
        })
    },

}

2.使用

file参数是一个二进制的流

async uploadBpmn2(params) {
            if(params.data.fileType && params.data.fileType.length>0){
                let formData = new FormData();
                formData.append("file", params.file);
                formData.append("fileType", params.data.fileType)
                console.log(formData);
                let res = await this.$http.upload("/ctrl/expertRegistration/uploadImage", formData)
                if (res.data && res.data.code == "200") {
                    let attValueText = ""
                    switch (params.data.fileType) {
                        case 6:
                            attValueText = "学历学位"
                            break;
                        case 7:
                            attValueText = "技术职称"
                            break;
                        case 8:
                            attValueText = "荣誉证书"
                            break;
                        case 9:
                            attValueText = "执业或执业资格证书"
                            break;
                        default:
                            break;
                    }
                    let fileMsg = {
                        "id": this.getRandomString(),
                        "name":params.file.name,
                        "infoId": null,
                        "attValue": params.data.fileType,
                        "attValueText": attValueText,
                        "filePath": "",
                        "base64": null,
                        "attValue": params.data.fileType,
                    }
                    fileMsg = Object.assign(fileMsg, res.data.data)
                    this.edArr[params.data.index].fileList.push(fileMsg)
    
                }
            }else{
                this.$message.error('请选择证书类型后上传');
            }
        },

文件上传: 1. 在 template 添加一个 input 标签,设置 type 为 file,用于选择要上传文件。 ``` <template> <div> <input type="file" @change="handleUpload"> </div> </template> ``` 2. 在 methods 添加 handleUpload 方法,获取选文件,使用 FormData 将其传递给后端。 ``` methods: { handleUpload(event) { const file = event.target.files[0] const formData = new FormData() formData.append('file', file) axios.post('/upload', formData) .then(response => { console.log(response) }) .catch(error => { console.log(error) }) } } ``` 3. 后端接收到文件后进行处理,返回上传成功的信息。 文件下载: 1. 在 template 添加一个 button 标签,用于触发下载操作。 ``` <template> <div> <button @click="handleDownload">下载文件</button> </div> </template> ``` 2. 在 methods 添加 handleDownload 方法,使用 axios 发送 GET 请求,将文件流返回给前端,使用 blob 对象将其下载到本地。 ``` methods: { handleDownload() { axios({ method: 'get', url: '/download', responseType: 'blob' }) .then(response => { const blob = new Blob([response.data]) const fileName = response.headers['content-disposition'].split('filename=')[1] const link = document.createElement('a') link.href = window.URL.createObjectURL(blob) link.download = fileName link.click() }) .catch(error => { console.log(error) }) } } ``` 3. 后端接收到下载请求后返回文件流,使用 Content-Disposition 响应头指定文件名。 ``` app.get('/download', (req, res) => { const filePath = path.join(__dirname, 'file.txt') const fileName = 'file.txt' res.setHeader('Content-Disposition', 'attachment; filename=' + fileName) const fileStream = fs.createReadStream(filePath) fileStream.pipe(res) }) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值