首页 > 编程语言 >微信小程序创建formdata对象,并通过 wx.request 发送file文件

微信小程序创建formdata对象,并通过 wx.request 发送file文件

时间:2024-01-11 10:33:59浏览次数:46  
标签:xml vnd text formdata request application ms 微信 audio

本文申明:仅作学习使用

需求:

  • 需要绕过wx.uploadFile进行图片的传输,通过接口给服务器

问题:

  • 因涉及到域名安全问题,不能使用 wx.uploadFile。
  • 微信本身没有FormData对象,无法使用 new FormData
  • 后端接口需要接收一个file, 所以只能想办法,通过wx.request 发送 multipart/form-data 请求

解决
在utils中引入formdata.jsmimeMap.js,并在使用页面调用

const FormData = require('./../../utils/formdata.js')
onChooseAvatar(e) {
    let params = e.detail.avatarUrl;
    console.log(params);
    //new一个FormData对象
    let formData = new FormData();
    //调用它的append()方法来添加字段或者调用appendFile()方法添加文件
    // formData.append("name", "value");
    formData.appendFile("filedata", params);
    let data = formData.getData();
    //添加完成后调用它的getData()生成上传数据,之后调用小程序的wx.request提交请求
    try {
      wx.request({
        url: 'http://xxx',
        method: 'POST',
        header: {
          'content-type': data.contentType
        },
        data: data.buffer,
        success: (res) => {}
      })
    } catch (error) {
      console.log(error)
    }
  },

formdata.js代码如下:

const mimeMap = require('./mimeMap.js')

function FormData(){
  let fileManager = wx.getFileSystemManager();
  let data = {};
  let files = [];

  this.append = (name, value)=>{
    data[name] = value;
    return true;
  }

  this.appendFile = (name, path, fileName)=>{
    let buffer = fileManager.readFileSync(path);
    if(Object.prototype.toString.call(buffer).indexOf("ArrayBuffer") < 0){
      return false;
    }

    if(!fileName){
      fileName = getFileNameFromPath(path);
    }

    files.push({
      name: name,
      buffer: buffer,
      fileName: fileName
    });
    return true;
  }

  this.getData = ()=>convert(data, files)
}

function getFileNameFromPath(path){
  let idx=path.lastIndexOf("/");
  return path.substr(idx+1);
}

function convert(data, files){
  let boundaryKey = 'wxmpFormBoundary' + randString(); // 数据分割符,一般是随机的字符串
  let boundary = '--' + boundaryKey;
  let endBoundary = boundary + '--';

  let postArray = [];
  //拼接参数
  if(data && Object.prototype.toString.call(data) == "[object Object]"){
    for(let key in data){
      postArray = postArray.concat(formDataArray(boundary, key, data[key]));
    }
  }
  //拼接文件
  if(files && Object.prototype.toString.call(files) == "[object Array]"){
    for(let i in files){
      let file = files[i];
      postArray = postArray.concat(formDataArray(boundary, file.name, file.buffer, file.fileName));
    }
  }
  //结尾
  let endBoundaryArray = [];
  endBoundaryArray.push(...endBoundary.toUtf8Bytes());
  postArray = postArray.concat(endBoundaryArray);
  return {
    contentType: 'multipart/form-data; boundary=' + boundaryKey,
    buffer: new Uint8Array(postArray).buffer
  }
}

function randString() {
  var result = '';
  var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  for (var i = 17; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
  return result;
}

function formDataArray(boundary, name, value, fileName){
  let dataString = '';
  let isFile = !!fileName;

  dataString += boundary + '\r\n';
  dataString += 'Content-Disposition: form-data; name="' + name + '"';
  if (isFile){
    dataString += '; filename="' + fileName + '"' + '\r\n';
    dataString += 'Content-Type: ' + getFileMime(fileName) + '\r\n\r\n';
  }
  else{
    dataString += '\r\n\r\n';
    dataString += value;
  }

  var dataArray = [];
  dataArray.push(...dataString.toUtf8Bytes());

  if (isFile) {
    let fileArray = new Uint8Array(value);
    dataArray = dataArray.concat(Array.prototype.slice.call(fileArray));
  }
  dataArray.push(..."\r".toUtf8Bytes());
  dataArray.push(..."\n".toUtf8Bytes());

  return dataArray;
}

function getFileMime(fileName){
  let idx = fileName.lastIndexOf(".");
  let mime = mimeMap[fileName.substr(idx)];
  return mime?mime:"application/octet-stream"
}

String.prototype.toUtf8Bytes = function(){
  var str = this;
  var bytes = [];
  for (var i = 0; i < str.length; i++) {
    bytes.push(...str.utf8CodeAt(i));
    if (str.codePointAt(i) > 0xffff) {
      i++;
    }
  }
  return bytes;
}

String.prototype.utf8CodeAt = function(i) {
  var str = this;
  var out = [], p = 0;
  var c = str.charCodeAt(i);
  if (c < 128) {
    out[p++] = c;
  } else if (c < 2048) {
    out[p++] = (c >> 6) | 192;
    out[p++] = (c & 63) | 128;
  } else if (
      ((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&
      ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {
    // Surrogate Pair
    c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
    out[p++] = (c >> 18) | 240;
    out[p++] = ((c >> 12) & 63) | 128;
    out[p++] = ((c >> 6) & 63) | 128;
    out[p++] = (c & 63) | 128;
  } else {
    out[p++] = (c >> 12) | 224;
    out[p++] = ((c >> 6) & 63) | 128;
    out[p++] = (c & 63) | 128;
  }
  return out;
};


module.exports = FormData;

mimeMap.js代码如下:

module.exports = {
  "0.001": "application/x-001",
  "0.323": "text/h323",
  "0.907": "drawing/907",
  ".acp": "audio/x-mei-aac",
  ".aif": "audio/aiff",
  ".aiff": "audio/aiff",
  ".asa": "text/asa",
  ".asp": "text/asp",
  ".au": "audio/basic",
  ".awf": "application/vnd.adobe.workflow",
  ".bmp": "application/x-bmp",
  ".c4t": "application/x-c4t",
  ".cal": "application/x-cals",
  ".cdf": "application/x-netcdf",
  ".cel": "application/x-cel",
  ".cg4": "application/x-g4",
  ".cit": "application/x-cit",
  ".cml": "text/xml",
  ".cmx": "application/x-cmx",
  ".crl": "application/pkix-crl",
  ".csi": "application/x-csi",
  ".cut": "application/x-cut",
  ".dbm": "application/x-dbm",
  ".dcd": "text/xml",
  ".der": "application/x-x509-ca-cert",
  ".dib": "application/x-dib",
  ".doc": "application/msword",
  ".drw": "application/x-drw",
  ".dwf": "Model/vnd.dwf",
  ".dwg": "application/x-dwg",
  ".dxf": "application/x-dxf",
  ".emf": "application/x-emf",
  ".ent": "text/xml",
  ".eps": "application/x-ps",
  ".etd": "application/x-ebx",
  ".fax": "image/fax",
  ".fif": "application/fractals",
  ".frm": "application/x-frm",
  ".gbr": "application/x-gbr",
  ".gif": "image/gif",
  ".gp4": "application/x-gp4",
  ".hmr": "application/x-hmr",
  ".hpl": "application/x-hpl",
  ".hrf": "application/x-hrf",
  ".htc": "text/x-component",
  ".html": "text/html",
  ".htx": "text/html",
  ".ico": "image/x-icon",
  ".iff": "application/x-iff",
  ".igs": "application/x-igs",
  ".img": "application/x-img",
  ".isp": "application/x-internet-signup",
  ".java": "java/*",
  ".jpe": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".jpg": "application/x-jpg",
  ".jsp": "text/html",
  ".lar": "application/x-laplayer-reg",
  ".lavs": "audio/x-liquid-secure",
  ".lmsff": "audio/x-la-lms",
  ".ltr": "application/x-ltr",
  ".m2v": "video/x-mpeg",
  ".m4e": "video/mpeg4",
  ".man": "application/x-troff-man",
  ".mdb": "application/msaccess",
  ".mfp": "application/x-shockwave-flash",
  ".mhtml": "message/rfc822",
  ".mid": "audio/mid",
  ".mil": "application/x-mil",
  ".mnd": "audio/x-musicnet-download",
  ".mocha": "application/x-javascript",
  ".mp1": "audio/mp1",
  ".mp2v": "video/mpeg",
  ".mp4": "video/mpeg4",
  ".mpd": "application/vnd.ms-project",
  ".mpeg": "video/mpg",
  ".mpga": "audio/rn-mpeg",
  ".mps": "video/x-mpeg",
  ".mpv": "video/mpg",
  ".mpw": "application/vnd.ms-project",
  ".mtx": "text/xml",
  ".net": "image/pnetvue",
  ".nws": "message/rfc822",
  ".out": "application/x-out",
  ".p12": "application/x-pkcs12",
  ".p7c": "application/pkcs7-mime",
  ".p7r": "application/x-pkcs7-certreqresp",
  ".pc5": "application/x-pc5",
  ".pcl": "application/x-pcl",
  ".pdf": "application/pdf",
  ".pdx": "application/vnd.adobe.pdx",
  ".pgl": "application/x-pgl",
  ".pko": "application/vnd.ms-pki.pko",
  ".plg": "text/html",
  ".plt": "application/x-plt",
  ".png": "application/x-png",
  ".ppa": "application/vnd.ms-powerpoint",
  ".pps": "application/vnd.ms-powerpoint",
  ".ppt": "application/x-ppt",
  ".prf": "application/pics-rules",
  ".prt": "application/x-prt",
  ".ps": "application/postscript",
  ".pwz": "application/vnd.ms-powerpoint",
  ".ra": "audio/vnd.rn-realaudio",
  ".ras": "application/x-ras",
  ".rdf": "text/xml",
  ".red": "application/x-red",
  ".rjs": "application/vnd.rn-realsystem-rjs",
  ".rlc": "application/x-rlc",
  ".rm": "application/vnd.rn-realmedia",
  ".rmi": "audio/mid",
  ".rmm": "audio/x-pn-realaudio",
  ".rms": "application/vnd.rn-realmedia-secure",
  ".rmx": "application/vnd.rn-realsystem-rmx",
  ".rp": "image/vnd.rn-realpix",
  ".rsml": "application/vnd.rn-rsml",
  ".rtf": "application/msword",
  ".rv": "video/vnd.rn-realvideo",
  ".sat": "application/x-sat",
  ".sdw": "application/x-sdw",
  ".slb": "application/x-slb",
  ".slk": "drawing/x-slk",
  ".smil": "application/smil",
  ".snd": "audio/basic",
  ".sor": "text/plain",
  ".spl": "application/futuresplash",
  ".ssm": "application/streamingmedia",
  ".stl": "application/vnd.ms-pki.stl",
  ".sty": "application/x-sty",
  ".swf": "application/x-shockwave-flash",
  ".tg4": "application/x-tg4",
  ".tif": "image/tiff",
  ".tiff": "image/tiff",
  ".top": "drawing/x-top",
  ".tsd": "text/xml",
  ".uin": "application/x-icq",
  ".vcf": "text/x-vcard",
  ".vdx": "application/vnd.visio",
  ".vpg": "application/x-vpeg005",
  ".vsd": "application/x-vsd",
  ".vst": "application/vnd.visio",
  ".vsw": "application/vnd.visio",
  ".vtx": "application/vnd.visio",
  ".wav": "audio/wav",
  ".wb1": "application/x-wb1",
  ".wb3": "application/x-wb3",
  ".wiz": "application/msword",
  ".wk4": "application/x-wk4",
  ".wks": "application/x-wks",
  ".wma": "audio/x-ms-wma",
  ".wmf": "application/x-wmf",
  ".wmv": "video/x-ms-wmv",
  ".wmz": "application/x-ms-wmz",
  ".wpd": "application/x-wpd",
  ".wpl": "application/vnd.ms-wpl",
  ".wr1": "application/x-wr1",
  ".wrk": "application/x-wrk",
  ".ws2": "application/x-ws",
  ".wsdl": "text/xml",
  ".xdp": "application/vnd.adobe.xdp",
  ".xfd": "application/vnd.adobe.xfd",
  ".xhtml": "text/html",
  ".xls": "application/x-xls",
  ".xml": "text/xml",
  ".xq": "text/xml",
  ".xquery": "text/xml",
  ".xsl": "text/xml",
  ".xwd": "application/x-xwd",
  ".sis": "application/vnd.symbian.install",
  ".x_t": "application/x-x_t",
  ".apk": "application/vnd.android.package-archive",
  "0.301": "application/x-301",
  "0.906": "application/x-906",
  ".a11": "application/x-a11",
  ".ai": "application/postscript",
  ".aifc": "audio/aiff",
  ".anv": "application/x-anv",
  ".asf": "video/x-ms-asf",
  ".asx": "video/x-ms-asf",
  ".avi": "video/avi",
  ".biz": "text/xml",
  ".bot": "application/x-bot",
  ".c90": "application/x-c90",
  ".cat": "application/vnd.ms-pki.seccat",
  ".cdr": "application/x-cdr",
  ".cer": "application/x-x509-ca-cert",
  ".cgm": "application/x-cgm",
  ".class": "java/*",
  ".cmp": "application/x-cmp",
  ".cot": "application/x-cot",
  ".crt": "application/x-x509-ca-cert",
  ".css": "text/css",
  ".dbf": "application/x-dbf",
  ".dbx": "application/x-dbx",
  ".dcx": "application/x-dcx",
  ".dgn": "application/x-dgn",
  ".dll": "application/x-msdownload",
  ".dot": "application/msword",
  ".dtd": "text/xml",
  ".dwf": "application/x-dwf",
  ".dxb": "application/x-dxb",
  ".edn": "application/vnd.adobe.edn",
  ".eml": "message/rfc822",
  ".epi": "application/x-epi",
  ".eps": "application/postscript",
  ".exe": "application/x-msdownload",
  ".fdf": "application/vnd.fdf",
  ".fo": "text/xml",
  ".g4": "application/x-g4",
  ".tif": "image/tiff",
  ".gl2": "application/x-gl2",
  ".hgl": "application/x-hgl",
  ".hpg": "application/x-hpgl",
  ".hqx": "application/mac-binhex40",
  ".hta": "application/hta",
  ".htm": "text/html",
  ".htt": "text/webviewhtml",
  ".icb": "application/x-icb",
  ".ico": "application/x-ico",
  ".ig4": "application/x-g4",
  ".iii": "application/x-iphone",
  ".ins": "application/x-internet-signup",
  ".IVF": "video/x-ivf",
  ".jfif": "image/jpeg",
  ".jpe": "application/x-jpe",
  ".jpg": "image/jpeg",
  ".js": "application/x-javascript",
  ".la1": "audio/x-liquid-file",
  ".latex": "application/x-latex",
  ".lbm": "application/x-lbm",
  ".ls": "application/x-javascript",
  ".m1v": "video/x-mpeg",
  ".m3u": "audio/mpegurl",
  ".mac": "application/x-mac",
  ".math": "text/xml",
  ".mdb": "application/x-mdb",
  ".mht": "message/rfc822",
  ".mi": "application/x-mi",
  ".midi": "audio/mid",
  ".mml": "text/xml",
  ".mns": "audio/x-musicnet-stream",
  ".movie": "video/x-sgi-movie",
  ".mp2": "audio/mp2",
  ".mp3": "audio/mp3",
  ".mpa": "video/x-mpg",
  ".mpe": "video/x-mpeg",
  ".mpg": "video/mpg",
  ".mpp": "application/vnd.ms-project",
  ".mpt": "application/vnd.ms-project",
  ".mpv2": "video/mpeg",
  ".mpx": "application/vnd.ms-project",
  ".mxp": "application/x-mmxp",
  ".nrf": "application/x-nrf",
  ".odc": "text/x-ms-odc",
  ".p10": "application/pkcs10",
  ".p7b": "application/x-pkcs7-certificates",
  ".p7m": "application/pkcs7-mime",
  ".p7s": "application/pkcs7-signature",
  ".pci": "application/x-pci",
  ".pcx": "application/x-pcx",
  ".pdf": "application/pdf",
  ".pfx": "application/x-pkcs12",
  ".pic": "application/x-pic",
  ".pl": "application/x-perl",
  ".pls": "audio/scpls",
  ".png": "image/png",
  ".pot": "application/vnd.ms-powerpoint",
  ".ppm": "application/x-ppm",
  ".ppt": "application/vnd.ms-powerpoint",
  ".pr": "application/x-pr",
  ".prn": "application/x-prn",
  ".ps": "application/x-ps",
  ".ptn": "application/x-ptn",
  ".r3t": "text/vnd.rn-realtext3d",
  ".ram": "audio/x-pn-realaudio",
  ".rat": "application/rat-file",
  ".rec": "application/vnd.rn-recording",
  ".rgb": "application/x-rgb",
  ".rjt": "application/vnd.rn-realsystem-rjt",
  ".rle": "application/x-rle",
  ".rmf": "application/vnd.adobe.rmf",
  ".rmj": "application/vnd.rn-realsystem-rmj",
  ".rmp": "application/vnd.rn-rn_music_package",
  ".rmvb": "application/vnd.rn-realmedia-vbr",
  ".rnx": "application/vnd.rn-realplayer",
  ".rpm": "audio/x-pn-realaudio-plugin",
  ".rt": "text/vnd.rn-realtext",
  ".rtf": "application/x-rtf",
  ".sam": "application/x-sam",
  ".sdp": "application/sdp",
  ".sit": "application/x-stuffit",
  ".sld": "application/x-sld",
  ".smi": "application/smil",
  ".smk": "application/x-smk",
  ".sol": "text/plain",
  ".spc": "application/x-pkcs7-certificates",
  ".spp": "text/xml",
  ".sst": "application/vnd.ms-pki.certstore",
  ".stm": "text/html",
  ".svg": "text/xml",
  ".tdf": "application/x-tdf",
  ".tga": "application/x-tga",
  ".tif": "application/x-tif",
  ".tld": "text/xml",
  ".torrent": "application/x-bittorrent",
  ".txt": "text/plain",
  ".uls": "text/iuls",
  ".vda": "application/x-vda",
  ".vml": "text/xml",
  ".vsd": "application/vnd.visio",
  ".vss": "application/vnd.visio",
  ".vst": "application/x-vst",
  ".vsx": "application/vnd.visio",
  ".vxml": "text/xml",
  ".wax": "audio/x-ms-wax",
  ".wb2": "application/x-wb2",
  ".wbmp": "image/vnd.wap.wbmp",
  ".wk3": "application/x-wk3",
  ".wkq": "application/x-wkq",
  ".wm": "video/x-ms-wm",
  ".wmd": "application/x-ms-wmd",
  ".wml": "text/vnd.wap.wml",
  ".wmx": "video/x-ms-wmx",
  ".wp6": "application/x-wp6",
  ".wpg": "application/x-wpg",
  ".wq1": "application/x-wq1",
  ".wri": "application/x-wri",
  ".ws": "application/x-ws",
  ".wsc": "text/scriptlet",
  ".wvx": "video/x-ms-wvx",
  ".xdr": "text/xml",
  ".xfdf": "application/vnd.adobe.xfdf",
  ".xls": "application/vnd.ms-excel",
  ".xlw": "application/x-xlw",
  ".xpl": "audio/scpls",
  ".xql": "text/xml",
  ".xsd": "text/xml",
  ".xslt": "text/xml",
  ".x_b": "application/x-x_b",
  ".sisx": "application/vnd.symbian.install",
  ".ipa": "application/vnd.iphone",
  ".xap": "application/x-silverlight-app",
  ".zip": "application/x-zip-compressed",
}

参考:
github源码
其他

标签:xml,vnd,text,formdata,request,application,ms,微信,audio
From: https://www.cnblogs.com/hei-xiu/p/17958003

相关文章

  • 微信小程序 宿主环境
        微信为小程序的正常运行提供了通信模型、运行机制、组件、API等的支持小程序的宿主环境就是微信,小程序里面所用的能力都是微信给咱们提供的     ......
  • 基于微信小程序的毕业设计-图书推荐系统(附源码+论文)
    了解设计+图片上号摘要:随着互联网的普及和信息技术的发展,图书推荐管理系统在图书馆中发挥着越来越重要的作用。本文基于SpringBoot框架,设计并实现了一个图书推荐管理系统。该系统能够根据用户的历史阅读记录和兴趣,为其推荐合适的图书,提高图书馆的借阅率。关键词:微信小程序;图书推荐;......
  • SAP ABAP技术文章合集_微信公众号:ABAP猿
    第1部分:ABAPOOALV相关文章合集序号文章标题01ABAPOOALV-基本显示02ABAPOOALV-排序、过滤03ABAPOOALV-合计、小计04ABAPOOALV-选择模式、触发事件05ABAPOOALV-隐藏列、修改列标题、添加图标列、调整列位置06ABAPOOALV-固定列、鼠标悬停文本......
  • 开屏广告?微信为何不随波逐流,坚持独特立场?
    嗨,亲爱的小米粉丝们!欢迎来到小米的微信公众号,我是你们的小米哥哥!今天我们要聊的话题可是相当火热,也颇具深度哦——腾讯产品面试题:为什么只有微信不做开屏广告?别着急,一起来揭开这个神秘面纱吧!首先,我们不得不承认,微信是一款为用户着想、注重用户体验的产品,我们一直秉持着"用户至上"的......
  • uniapp微信小程序-底部tabBar颜色显示问题
    uniapp微信小程序-底部tabBar颜色显示问题在HbuilderX上开发的时候,页面运行在H5端的底部tabBar显示都没问题,但在运行到微信开发者工具时出现底部tabBar实际文字颜色与H5效果不同的问题。检查page.json文件。"tabBar":{ "borderStyle":"white", "backgroundColor......
  • 使用Python的requests库在Linux中进行HTTP通信
    在Linux中,使用Python的requests库进行HTTP通信是一种高效且简洁的方法。requests库为发送HTTP请求提供了丰富的功能,包括GET、POST、PUT、DELETE等常见的HTTP方法,以及处理cookies、会话、参数等高级功能。首先,确保您的Linux系统已经安装了Python和requests库。如果尚未安装,可以使用......
  • php对接微信小程序支付
    基本流程:申请商户平台账号 微信小程序绑定已有商户号并开通微信支付登录商户平台对小程序授权,下载支付证书,记录商户号,支付密钥。阅读微信支付官方文档,完成接口的对接编码。开发支付流程:微信小程序的基本配置。(app_id[小程序唯一id],mch_id[商户号],md5_key[支付密钥],notify_url[......
  • AI壁纸画展头像表情包流量主微信抖音小程序开源版开发
    AI壁纸画展头像表情包流量主微信抖音小程序开源版开发以下是AI壁纸画展头像表情包流量主微信抖音小程序开源版的开发功能列表:用户注册和登录:实现用户注册和登录功能,包括手机号登录、第三方登录等方式。图片上传和展示:用户可以上传自己的图片或选择系统提供的图片进行展示,支持图片......
  • ArkUI实现微信主页布局
    一、Tabs实现页面切换项目整体效果如下:修改Index.ets,实现选项卡切换页面,内容如下:import{NoteBookComponent}from'../components/NoteBookComponent'import{FoundComponent}from'../components/FoundComponent'import{MeComponent}from'../components/MeCompone......
  • pytest-yaml 测试平台-4.生成allure报告,报告反馈企业微信、钉钉、飞书通知
    前言定时任务执行完成后生成可视化allure报告,并把结果发到企业微信,钉钉,飞书通知群里。生成allure报告添加定时任务执行完成后生成allure报告查看报告详情报告会显示详细的request和response详细信息也可以查看log日志报告反馈-企业微信创建定时任务时添加企业微信token企业微信t......