求助:小程序如何使用FormData传二进制文件(binary)?

小程序 文章 2022-02-21 17:40 2143 0 全屏看文

AI助手支持GPT4.0

求助:小程序如何使用FormData传二进制文件(binary)?Help: How does the applet use FormData to transfer binary files?

求助:小程序如何使用FormData传二进制文件(binary)?

**背景:在飞书小程序开发(和微信小程序类似),需要获取到文本的图片信息,请求飞书接口返回的图片信息是一个二进制流,获取获取blob一个对象。需要把这个图片数据上传到公司的服务器上,变成自己公司的图片。

**公司的接口数据

--需要的数据效果在Google控制台效果是这样的

--请求头有用boundary包裹

--这个接口是原来存在的,在vue项目里可以跑通,现在我在小程序里面调用这个接口数据就传不过去。

**我获取到的数据形式

--在小程序里我能获取到图片的二进制流数据或者blob对象,如下

或这种格式

**Background: in the development of flybook applet (similar to wechat applet), it is necessary to obtain the picture information of the text. The picture information returned by the request flybook interface is a binary stream and an object of blob is obtained. You need to upload this image data to the company's server and turn it into your own company's image** In the past, the effect of calling the data of the company's vBoy interface is that the data of the company's request can run through the console. In this way, the data can run through this interface. In the past, the data of the company's request can run through this interface. In this way, the data can run through this interface** The data form I get -- in the applet, I can get the binary stream data or blob object of the picture, as follows or in this format

回答:

社交恐怖分z:
wx.chooseImage({  count: 1, // 默认9  sizeType: ["compressed"], // 可以指定是原图还是压缩图,默认二者都有  sourceType: ["album", "camera"], // 可以指定来源是相册还是相机,默认二者都有  success: (res) => {    // 返回选定照片的本地文件路径列表,tempFilePath可以作为image标签的src属性显示图片    var tempFilePaths = res.tempFilePaths;    var tempFilesSize = res.tempFiles[0].size; //获取图片的大小,单位B    if (tempFilesSize <= 3000000) {      //图片小于或者等于3M时 可以继续      wx.uploadFile({        url: 'xxx',        filePath: res.tempFilePaths[0],        name: "xxx",        header: {          chartset: "utf-8",          "content-type": "multipart/form-data"        },        formData: {          token: xxx        },        success: (res) => {    },        fail: function(e) {        }      })    } else {      wx.showToast({        title: "上传图片不能大于3M哦~",        icon: "error"      })    }  }});
菜菜:

两种尝试过的失败效果

1.手动凭借请求头

菜菜:第二种
Mr.Zhao:

不要对返回值进行编码

菜菜:亲什么意思呢,我直接请求获取的是那一串乱码,加个response-type:blob,然后飞书返回的就是一个blob对象
Mr.Zhao:
Mr.Zhao:用wx.request获取buffer 然后文件api保存到本地获取临时路径然后wx.uploadFile上传。
还可以用wx.downloadFile下载获取临时路径然后wx.uploadFile上传.
菜菜:亲我现在获取到了数据,不能拿找个数据以我想要的格式Form data,upload_file: (binary)这样请求啊。我试了第一种方法,但是不确定下载路径怎么写,而且已经有了数据再把它存到本地再处理,请求图片数据多了这样是不是不太合理呢
Mr.Zhao:多看看文档吧

-EOF-

AI助手支持GPT4.0