码迷,mamicode.com
首页 > 其他好文 > 详细

模拟FormData创建表单请求

时间:2020-07-16 21:01:41      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:cto   fun   readasa   sed   header   array   har   webkit   ati   





class AppendStatus{
    successed = false;
    constructor(){

    }
    success(listenEvent){
        this.successed = true;
        if(listenEvent){
            listenEvent.run();
        }
    }
    getStatus(){
        return !!this.successed
    }
}

class ListenEvent{
    callback;
    appendStatusCache = [];
    isRuned = false;
    constructor(callback = ()=>{},appendStatusCache = []){
        this.callback = callback;
        this.appendStatusCache = appendStatusCache;
    }
    run(){
        var ct = 0;
        for(var i =0,l=this.appendStatusCache.length;i<l;i++){
            if(this.appendStatusCache[i].getStatus()){
                ct +=1;
            };
        };
        if(ct >= this.appendStatusCache.length && !this.isRuned){
          console.log("run success",ct);
            this.callback();
            this.isRuned = true;
        }
    }
}
class OurFormData {
    // data;
    rs;
    callback;
    appendStatusCache = [];
    listenEvent;
    constructor(rs) {
        // this.data = data;
        this.rs = rs;
        // this.callback = callback;
    }

    append(k,v){
        var appendStatus = new AppendStatus();
        this.appendStatusCache.push(appendStatus);
        
        let data_string = ‘\r\n‘
        this.segments = []
        // this.rs = rs
        this.status = 0
        let resolve = ()=>{
            appendStatus.success(this.listenEvent);
        }
        // let result = new Promise(res => resolve = res)
        
        // let k, v
        let getTag = v => ({}).toString.call(v)
        // for ([k, v] of Object.entries(data)) {
        // }
        let tag = getTag(v)
        console.log("append2",k,v,tag);
        if (tag === ‘[object File]‘) {
          // 单文件
          let render = new FileReader()
          render.readAsBinaryString(v);
          // render.index = this.segments.length
          var index;

          render.onload = ({
            target: {
              result
            }
          }) => {
            console.log("onload",k,v,tag);
            this.segments[index] += `${result || ‘‘}\r\n`;
            // this.status--

            // 所有异步全部完成
            if (this.status === 0) {
              resolve()
            }
          }

          
          index = this.segments.push(
            `------WebKitFormBoundary${this.rs||‘‘}\r\nContent-Disposition: form-data; name="${k || ‘‘}"; filename="${v.name || ‘‘}"\r\nContent-Type: "${v.type || ‘‘}"\r\n\r\n`
          )
        //   this.status++
        } else if (tag === ‘[obejct Array]‘ && v.length > 0 && getTag(v[0]) === ‘[object File]‘) {
          // 多文件
          let file, render
          for (file of v) {
            render = new FileReader()
            render.readAsBinaryString(file);
            var index;

            render.onload = ({
              target: {
                result
              }
            }) => {
              this.segments[index] += `${result||‘‘}\r\n`
            //   this.status--

              // 所有异步全部完成
              if (this.status === 0) {
                resolve()
              }
            }

            index = this.segments.push(
              `------WebKitFormBoundary${this.rs||‘‘}\r\nContent-Disposition: form-data; name="${k || ‘‘}"; filename="${v.name || ‘‘}"\r\nContent-Type: "${v.type||‘‘}"\r\n\r\n`
            )
            // this.status++
          }
        } else if(tag === ‘[object ArrayBuffer]‘){
            console.log("[object ArrayBuffer]",v);
        } else if (tag === ‘[object Array]‘) {
          // 处理数组, age: [12, 14]
          let $_
          for ($_ of v) {
            this.segments.push(
              `------WebKitFormBoundary${this.rs||‘‘}\r\nContent-Disposition: form-data; name="${k||‘‘}"\r\n\r\n${$_||‘‘}\r\n`
            )
          }
          resolve()
        } else {
          // string and number
          this.segments.push(
            `------WebKitFormBoundary${this.rs||‘‘}\r\nContent-Disposition: form-data; name="${k||‘‘}"\r\n\r\n${v||‘‘}\r\n`
          )
          resolve()
        }
        // if (this.status === 0) {
        //   resolve(this.handleResData(this.segments))
        // }
        // return result
    }

    handleResData(segments = this.segments) {
        segments.unshift(`\r\n`)
        segments.push(`------WebKitFormBoundary${this.rs||‘‘}--`)
        let data = segments.join(‘‘)

        let bytes = data.length
        console.log("handleResData",segments,bytes);
        // let view = new Uint8Array(bytes)
        // for (let i = 0; i < bytes; i++) {
        //   view[i] = data.charCodeAt(i) & 0xff
        // }
        let buffer = new ArrayBuffer(bytes)
        let view = new DataView(buffer, 0)
        let i
        for (i = 0; i < bytes; i++) {
        // & 0xff https://www.cnblogs.com/think-in-java/p/5527389.html
        // view.setUint8(i, data.charCodeAt(i) & 0xff)
        view.setUint8(i, data.codePointAt(i) & 0xff)
        }
        return view
    }

    ready(callback){
        this.listenEvent = new ListenEvent(callback,this.appendStatusCache);
        this.listenEvent.run();
    }
}


    return new Promise((res,rej) =>{
        
        //   let data = {
        //     name: ‘ajanuw‘,
        //     age: [1,2]
        //   }
        // Object.assign(data, {
        //   file
        // })

        let rs = Date.now().toString(16)
        let sendData = new OurFormData(rs)
        try{
          
            var reader = new FileReader();
            reader.readAsArrayBuffer(file);
            reader.onload = function (e) {
                console.info(reader.result); //ArrayBuffer {}
                //经常会遇到的异常 Uncaught RangeError: byte length of Int16Array should be a multiple of 2
                //var buf = new int16array(reader.result);
                //console.info(buf);

                //将 ArrayBufferView  转换成Blob
                var buf = new Uint8Array(reader.result);
                
                sendData.append("file",reader.result);
                sendData.ready(()=>{
                    var formData = sendData.handleResData();



                    console.log("new beforeUpload222",sendData,formData)
                    fetch(this.$uploadUrl, {
                        method: ‘POST‘, // or ‘PUT‘
                        body: formData,
                        headers: new Headers({
                          // ‘Content-Type‘: ‘multipart/form-data‘
                          // ‘Content-Type‘: ‘application/json‘
                          "Content-Type":`multipart/form-data; boundary=----WebKitFormBoundary${rs||‘‘}`
                        })
                      }).then(res => res.json())
                      .catch(error => console.error(‘Error:‘, error))
                      .then(response => console.log(‘Success:‘, response));
                })
            }
            
        }catch(e){
          console.log("Error:",e)
        }
        rej();
      })

模拟FormData创建表单请求

标签:cto   fun   readasa   sed   header   array   har   webkit   ati   

原文地址:https://www.cnblogs.com/ksyy/p/13324026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!