记录一下在小程序中put文件
第一步,wx.chooseMessageFile,获取上传的文件的临时路径;
第二步, wx.getFileSystemManager().readFile,读取文件ArrayBuffer;
第三步,构造一个multi/formdata格式的请求,boundary头部和boundary尾部;
第四步,将boundary头部、文件ArrayBuffer、boundary尾部转换成Array,并按顺序拼接到一起;
第五步,将最终结果转换为Uint8Array;
第六步,put请求
供参考
、、、
wx.chooseMessageFile({
count: 6,
type: ‘all’,
success(res) {
var tempFilePaths = res.tempFiles;
var filename = tempFilePaths[0].name;
wx.getFileSystemManager().readFile({
filePath: tempFilePaths[0].path,
success:fileStream=>{
var fileArray = new Uint8Array(fileStream.data);
var start_boundary = ‘\r\n–yourboundary\r\n’ + ‘Content-Disposition: form-data; name=“data”; filename="’ + yourfilename+ ‘"\r\n’+‘Content-Type:application/octet-stream’ +’\r\n\r\n’ ;
var end_boundary = ‘\r\n–yourboundary–’;
var startArray = [];
for (var i = 0; i < start_boundary.length; i++) {
startArray.push(start_boundary.charCodeAt(i));
}
var endArray = [];
for (var i = 0; i < end_boundary.length; i++) {
endArray.push(end_boundary.charCodeAt(i));
}
var totalArray = startArray.concat(Array.prototype.slice.call(fileArray), endArray);
var typedArray = new Uint8Array(totalArray);
wx.request({
url: ‘yoururl’,
method: ‘PUT’,
header: {
‘content-type’: ‘multipart/form-data; boundary=yourboundary’
},
data: totalArray.buffer,
success: function (res) {
…
}})
}})
}
)}
、、、
为啥不用wx.uploadFile
totalArray.buffer是undefined
这样做就没办法做到上传进度的监听
问一下 boundary这个是怎么生成的
你好,楼主,如果只是put数据不加文件的话,应该怎样编写?这是我按照您的格式改的,可以正常访问url,但是更新不了数据,求解答,感激不尽!