小程序arraybuffer转中文

pc端是 我得改写到uniapp上

const getCSVFile = async (block)=>{
    let url  = block.content;
    // let url = v.content.replace(window.__env__.VITE_API_URL_QUERY,"");
    let res = await rDownload(url);
    const blobData = [res.data];

    console.log('blobData', blobData)
      
	  const file = new Blob(blobData, { type: 'application/octet-stream' }); 
    const reader = new FileReader();
    reader.onload = () => { 
        const text = reader.result;
        fixedTableData(block,text);
       
    };
     
    reader.readAsText(file,'gbk');

}
const fixedTableData = (v,rs)=>{  
  let rows = rs.split(/\r\n/);
  console.log('rows', rows)
  v.tableConfig=(rows[0].split(",")).map((item,i)=>({dataIndex:'r'+i ,name:item}));
  v.tableData = []; 
  rows.forEach((element,j) => {
    if(j>0 && element&& j<11){
       let row:{[key:number]:string} = {}; 
       (element.split(",")).forEach((item,i)=>{
        row['r'+i] = item;
      })
      v.tableData.push(row)
    }  
  });
  
}

首先 uni.request我试过不能传responseType: 'blob',只能responseType: 'arraybuffer'

然后拿到res.data是arraybuffer格式的 小程序不能用new Blob() 

const myTypedArray = new Uint8Array(buffer);

const str = String.fromCharCode(...myTypedArray);

然后得到一串乱码

换个办法, cnpm install text-encoding-shim

然后 在文件中   import * as TextEncoding from 'text-encoding-shim';

const myTypedArray = new Uint8Array(buffer);

const str = new TextEncoding.TextDecoder('utf-8').decode(myTypedArray)

得到另一串乱码

然后发现电脑端用的gbk 

const myTypedArray = new Uint8Array(buffer);

const str = new TextEncoding.TextDecoder('gbk ').decode(myTypedArray)

好了能用了

以下是源代码

async getCSVFile (block){
			    // let url  = block.content;
				let url  =  block.content.replace('/cls','http://123.158.253.87:9407/cls')
				console.log('url', url)
			   
				
				uni.request({
					url: url,
					method: 'GET',
					// data: {},
					responseType: 'arraybuffer',
					// responseType: 'blob',
					success: (res) => {
						 
						var buffer = res.data
						
						const myTypedArray = new Uint8Array(buffer)
						// const str = String.fromCharCode(...myTypedArray)
						// const str = new TextEncoding.TextDecoder('utf-8').decode(myTypedArray)
						let str = new TextEncoding.TextDecoder("gbk").decode(myTypedArray)
						console.log(str)
						this.fixedTableData(block, str)
						
				
					},
					fail: (err) => {
						console.log(err)
						//_self.tips="网络错误,小程序端请检查合法域名";
					},
				});
			    // let res = await rDownload(url);
			   
			
			},

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值