發現微信小程序的wx.request無法post提交上傳文件.
1.是微信小程序沒有提供fromdata對象,(也就是無法把表單的內容封裝成fromdata數據)
2.微信小程序也沒有file的表單元素。(應該騰訊不想我們通過wx.request上傳文件,讓我們用wx.upload去每次一個一個的上傳)
=======================
其實也並非wx.request就無法上傳文件,只要按照multipart/form-data提交數據的格式封裝數據即可(說白了就是字符串拼接)
下面找的multipart/form-data提交數據時的格式:
備注:其他提交數據格式( https://blog.csdn.net/qq_33706382/article/details/78168325 )
網上一些前輩就是用此思路.(把提交的數據按照規定格式拼接即可)
https://developers.weixin.qq.com/community/develop/article/doc/0000cc0e5bc5d093c6f8be17254c13
https://blog.csdn.net/qq_42092177/article/details/104927394
wx.request({ url:'http://localhost:8080/test/multipart-form', method:'POST', header: { 'content-type':'multipart/form-data; boundary=XXX' }, data:'\r\n--XXX' + '\r\nContent-Disposition: form-data; name="field1"' + '\r\n' + '\r\nvalue1' + '\r\n--XXX' + '\r\nContent-Disposition: form-data; name="field2"' + '\r\n' + '\r\nvalue2' + '\r\n--XXX--' })
//其中XXX就是分隔符,可以隨便設置.(如果用瀏覽器的話分隔符是用一定算法生成的)
到這里我們大概知道了,微信的wx.request,只要把提交的數據拼接好,按照對應的請求頭提交數據,是可以上傳文件的。
我在網上找了下,有兩種實現方法:
封裝請求:https://github.com/supperchong/wx-multipart
封裝fromdata: https://github.com/zlyboy/wx-formdata
一. 是直接封裝請求,這個返回的是Promise對象,用法:
https://github.com/supperchong/wx-multipart
// 引入js文件 const Multipart = require('../../utils/Multipart.min.js') const fields=[{ name:'username', value:'小黃' },{ name:'number', value:'13812345678' }]; const files= [ { name: "img1", filePath: "http://tmp/wx07dfb4391.png" }, { name: "img2", filePath: "http://tmp/wx07dfb4392.png" }, { name: "img3", filePath: "http://tmp/wx07dfb4393.png" } ]; let result = new Multipart({ files, fields }).submit('http://localhost/wx_multipart/mini/upload'); result.then(function (res) { //請求結果 console.log(res); });
二.封裝fromdata的更簡單了,引入js后
const FormData = require('./formData.js') //new一個FormData對象 let formData = new FormData(); //調用它的append()方法來添加字段或者調用appendFile()方法添加文件 formData.append("name", "value"); formData.appendFile("file", filepath); let data = formData.getData(); //添加完成后調用它的getData()生成上傳數據,之后調用小程序的wx.request提交請求 wx.request({ url: 'https://接口地址', header: { 'content-type': data.contentType }, data: data.buffer, });
轉和參:
https://blog.csdn.net/CodingNoob/article/details/81176892
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects
https://ec.haxx.se/http/http-multipart
https://developers.weixin.qq.com/community/develop/article/doc/0000cc0e5bc5d093c6f8be17254c13
https://blog.csdn.net/qq_42092177/article/details/104927394
https://juejin.cn/post/6844903752604844045