美文网首页
JS-异步上传文件

JS-异步上传文件

作者: ITtian | 来源:发表于2017-03-06 15:39 被阅读37次
    使用封装好的ajax方法的时候,发现并不能将文件上传过去,于是就使用表单上传的方法,直到发现了formdata

    IT TianSir

    /**
     * 上传文件请求
     * @param url   请求地址(string)
     * @paramList paramsList  传到后台的参数列表(Array)
     * @param type   请求类型(string)
     * @param callback   回调函数(function)
     */
    uploadFile(url,paramsList,type,callback){
        const token = JSON.parse(localStorage.getItem('token'))
        if (token === null || token.created_at + token.expires_in < new Date().getTime() / 1000 || token === {}) {
            return this.getToken().then((response) => {
                const data = response.data
                const tokenObj = {
                    created_at: data.created_at,
                    expires_in: data.expires_in,
                    access_token: data.access_token
                }
    
                localStorage.setItem('token', JSON.stringify(tokenObj))
                let formData = new FormData()
                let xhr = new XMLHttpRequest()
    
                formData.append('access_token',data.access_token)
    
                for(let item in paramsList){
                     if(paramsList[item] instanceof Array){
                         // 数组需要这样传递
                           for(let obj of paramsList[item]){
                             formData.append(`${item}[]`, obj)
                          }
                     }else{
                         formData.append(item, paramsList[item])
                    }
                }
    
                xhr.onreadystatechange = ()=>{
                    if(xhr.readyState === 4){
                        if(xhr.status === 200){
                            callback(xhr.response)
                        }else{
                            callback(xhr.response)
                        }
                    }
                }
    
                xhr.open(type,url,true)
                xhr.send(formData)
    
            }).catch((res) => {
                console.log(res)
            })
        } else {
            let formData = new FormData()
            let xhr = new XMLHttpRequest()
    
            formData.append('access_token',token.access_token)
    
            if(paramsList[item] instanceof Array){
                  // 数组需要这样传递
                  for(let obj of paramsList[item]){
                     formData.append(`${item}[]`, obj)
                  }
            }else{
                  formData.append(item, paramsList[item])
            }
    
            xhr.onreadystatechange = ()=>{
                if(xhr.readyState === 4){
                    if(xhr.status === 200){
                        callback(xhr.response)
                    }else{
                        callback(xhr.response)
                    }
                }
            }
    
            xhr.open(type,url,true)
            xhr.send(formData)
        }
    }```
    
    + ```使用 let formData = new FormData() 实例化一个表单数据对象```
    + ```使用 let xhr = new XMLHttpRequest() 实例化一个异步的对象```
    + ```formData.append(param_name,param_value)将参数添加进去```
    + ```最后一步,发送三部曲,设置状态监听事件,打开连接,发送```
    + ```在发送成功的时候,执行传过来的回调函数```
    
    最后,使用的方法大致如下:
    
    

    uploadFile(url, params, 'post', res => {
    const status = res.status
    if (status.code === '20000') {
    // 执行成功后的操作
    } else {
    // 失败后的操作
    }
    )

    相关文章

      网友评论

          本文标题:JS-异步上传文件

          本文链接:https://www.haomeiwen.com/subject/bvkugttx.html