uniapp-文件上传

发布时间 2023-09-15 13:27:45作者: vba是最好的语言

一 使用uni.uploadFile

 二 具体实现案例

<template>
    <view class="container">
        主页
        <button @click="getInfo()">测试接口</button>
    </view>


    <view>
        <uni-section title="选择图片" type="line">
            <view class="file-select">
                <uni-file-picker v-model="imageValue" file-mediatype="image" mode="grid" file-extname="png,jpg"
                    :limit="1" @progress="progress" @success="success" @fail="fail" @select="select" @delete="delete" />
            </view>
            <view class="file-upload">
                <button @click="upload">上传文件</button>
            </view>
        </uni-section>
    </view>


</template>

<script>
    import {
        info,
        uploadSelectedFile
    } from "@/services/index.js"
    import {
        uploadFile
    } from "../../utils/request"
    export default {
        data() {
            return {
                imageValue: [],
                imageStyles: {
                    width: 64,
                    height: 64,
                    border: {
                        radius: '50%'
                    }
                },
                listStyles: {
                    // 是否显示边框
                    border: true,
                    // 是否显示分隔线
                    dividline: true,
                    // 线条样式
                    borderStyle: {
                        width: 1,
                        color: 'blue',
                        style: 'dashed',
                        radius: 2
                    }
                }
            }
        },
        onLoad() {
            // this.getInfo()
        },
        methods: {
            upload() {
                const fileInfo = this.$refs.files
                const tempFilePath = this.$refs.tempFiles
                console.log(fileInfo)
                console.log('tempFilePath文件信息:')
                console.log(tempFilePath)
            },
            async getInfo() {
                let res = await info();
            },
            // 获取上传状态
            async select(e) {
                console.log('选择文件:', e)
                const tempFilePaths = e.tempFilePaths;
                const uploaddata = await uploadSelectedFile(tempFilePaths[0], {})
                // 下面3个值是uni-app规定的一个不能少
                let x = {}
                x.url = uploaddata.url
                x.extname = ''
                x.name = uploaddata.filename
                this.imageValue.push(x)
            },
            // 获取上传进度
            progress(e) {
                console.log('上传进度:', e)
            },
            // 上传成功
            success(e) {
                console.log('上传成功')
            },
            // 上传失败
            fail(e) {
                console.log('上传失败:', e)
            },
            // 删除
            delete(e) {
                console.log('删除图片:', e)
            }
        }
    }
</script>

<style>
    .container {
        padding: 20px;
        font-size: 14px;
        line-height: 24px;
    }

    .file-select {
        padding: 10px;
        padding-top: 0;
    }
</style>

接口处理方法

import {toast, clearStorageSync, getStorageSync, useRouter, isObject} from '@/utils/utils.js'
import {BASE_URL} from '@/config/index.js'
import RequestManager from './RequestManager.js'

const manager = new RequestManager()

// 添加拦截器
const httpInterceptor = {
    invoke(options)
    {
        if (!options.url.startsWith('http'))
        {
            options.url = BASE_URL + options.url
        }
        options.timeout = 10000;
        // token
        const token = getStorageSync("token")
        if(token)
        {
            options.header.token = token;
        }
    }
}

uni.addInterceptor("request", httpInterceptor)
uni.addInterceptor("uploadFile", httpInterceptor)

const baseRequest = async (url, method, data = {}, loading = true) =>{
    let requestId = manager.generateId(method, url, data)
    // 避免在同一时间内请求次数过多,上一个没有结束
    if(!requestId) {
        console.log('重复请求')
    }
    if(!requestId) return false;
    
    return new Promise((reslove, reject) => {
        loading && uni.showLoading({title: 'loading'})
        uni.request({
            url: url,
            method: method || 'GET',
            data: data || {},
            success: (successData) => {
                const res = successData.data
                if(res.code == 200){
                    reslove(res.data)
                }
                else if(res.code == 401){
                    // 清除用户信息
                    clearStorageSync("123")
                    toast('未登录,请先登录')
                    reject(res)
                }
                else{
                    toast('网络连接失败,请稍后重试')
                    reject(res)
                }
            },
            fail: (msg) => {
                toast('网络连接失败,请稍后重试')
                reject(msg)
            },
            complete: ()=>{
                uni.hideLoading()
                manager.deleteById(requestId)
            }
        })
    })
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
    request[method] = (api, data, loading) => baseRequest(api, method, data, loading)
})

// 上传文件
const uploadFile = async (url, filePath, formdata = {}, loading = true) =>{
    let requestId = manager.generateId("post", url, formdata)
    // 避免在同一时间内请求次数过多,上一个没有结束
    if(!requestId) {
        console.log('重复请求')
    }
    if(!requestId) return false;
    
    return new Promise((reslove, reject) => {
        loading && uni.showLoading({title: 'loading'})
        uni.uploadFile({
            url: url,
            formData: formdata || {},
            filePath: filePath,
            success: (successData) => {
                let res = {}
                if(!isObject(successData.data))
                {
                    res = JSON.parse(successData.data)
                }
                if(res.code == 200){
                    reslove(res.data)
                }
                else if(res.code == 401){
                    // 清除用户信息
                    clearStorageSync("123")
                    toast('未登录,请先登录')
                    reject(res)
                }
                else{
                    toast('网络连接失败,请稍后重试')
                    reject(res)
                }
            },
            fail: (msg) => {
                toast('网络连接失败,请稍后重试')
                reject(msg)
            },
            complete: ()=>{
                uni.hideLoading()
                manager.deleteById(requestId)
            }
        })
    })
}

export  {request,uploadFile}
// 上传文件
export const uploadSelectedFile = (filePath, formData) => uploadFile("/File/Upload",filePath,formData)
/**
 * 判断参数是否是对象
 * @param {String} obj 参数
 */
export function isObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]'
}