Skip to content

JS实现base64图片上传功能

完整代码

这里主要是以uniapp为示例,原理一样

先将base64图片转化为本地文件地址

js
/**
 * 将base64图片转化为图片本地文件地址
 * @param {*} base64 
 * @returns 
 */
export function base64ToPath(base64) {
    return new Promise(function (resolve, reject) {
        if (typeof window === 'object' && 'document' in window) {
            base64 = base64.split(',')
            var type = base64[0].match(/:(.*?);/)[1]
            var str = atob(base64[1])
            var n = str.length
            var array = new Uint8Array(n)
            while (n--) {
                array[n] = str.charCodeAt(n)
            }
            return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
        }
        var extName = base64.match(/data\:\S+\/(\S+);/)
        if (extName) {
            extName = extName[1]
        } else {
            reject(new Error('base64 error'))
        }
        var fileName = Date.now() + '.' + extName
        if (typeof plus === 'object') {
            var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
            bitmap.loadBase64Data(base64, function () {
                var filePath = '_doc/uniapp_temp/' + fileName
                bitmap.save(filePath, {}, function () {
                    bitmap.clear()
                    resolve(filePath)
                }, function (error) {
                    bitmap.clear()
                    reject(error)
                })
            }, function (error) {
                bitmap.clear()
                reject(error)
            })
            return
        }
        if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
            var filePath = wx.env.USER_DATA_PATH + '/' + fileName
            wx.getFileSystemManager().writeFile({
                filePath: filePath,
                data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
                encoding: 'base64',
                success: function () {
                    resolve(filePath)
                },
                fail: function (error) {
                    reject(error)
                }
            })
            return
        }
        reject(new Error('not support'))
    })
}

即可调用正常的文件上传流程,忽略业务代码,关注path字段

js
export function base64Upload(base64,formData = {}) {
    const self = this
    return new Promise((resolve, reject) => {
        base64ToPath(base64)
            .then(path => {
                uni.uploadFile({
                    header: { "Ark-Auth": getToken() || "" },
                    url: Env.NODE_ENV === "development" ? "/api/system-files/addFileStream" : Env.API_URL + '/system-files/addFileStream',
                    filePath: path,
                    name: 'file',
                    formData,
                    fail(e) {
                        self.$message.error("图片上传失败!" + e.errMsg())
                    },
                    success(res2) {
                        resolve(res2)
                    }
                })
            })
            .catch(error => {
                console.error(error)
            })
    })
}

上次更新于: