使用Suitescript实现与带有表单数据的CURL POST相同的功能

问题描述

在这里寻找Suitescript / Javascript专家,以向我指出正确的方向。我正在创建连接到第三方API的计划脚本,并且该API调用要求使用多部分表单数据通过HTTP.POST提交GZIP文件。我已经通过CURL进行了测试,所以我知道我的数据是有效的。这是CURL测试:

curl --location --request POST 'https://dev.themarket.co.nz/api/product/sku/sheet/upload' \
--header 'Content-Type: multipart/form-data' \
--header 'Authorization: <tokem goes here>  ' \
--form 'data={"MerchantId": "5233","Overwrite": 1,"FileFormatCode": "JSON","SourceChannel": "MERCHANT","SourceOrg": "Shop Until","IgnoreExistingImage": 1 }' \
--form 'file=@/Users/tim/inventory.json.gz'

要在Suitescript中创建等效项,我正在手工编码数据,因为Suitescript没有创建多部分表单数据的功能。这很好,我可以成功地将API调用提交给远程系统,并且系统正确读取主体数据并提取消息的各个部分。但是消息的第二部分是GZIP文件,该文件内容已损坏。我不知道如何从Netsuite的文件柜中提取文件并以正确的方式编码内容。我想我缺少编码步骤了吗?

这是我的代码段,下面是正文的外观。

var gz_content = gzippedFile.getContents();
var body = [];   
body.push('--' + boundary);
body.push('Content-disposition: form-data; name="data"');
body.push('');
body.push(form_data);
body.push('--' + boundary);
body.push('Content-disposition: form-data; name="file"; filename="inventory.json.gz"');
body.push('Content-Type: application/x-gzip');
body.push('');
body.push(gz_content);     
body.push('--' + boundary + '--');
body.push('');
             
  response = https.post({ 
          url: api_call,headers: headers_themarket,body: body.join('\r\n')
  });

这是多部分内容的样子:

--70834bf1-1439-4681-b1d4-fb3fa1f9efef

Content-disposition: form-data; name="data"



{"MerchantId": "5233","IgnoreExistingImage": 1 }

--70834bf1-1439-4681-b1d4-fb3fa1f9efef

Content-disposition: form-data; name="file"; filename="inventory.json.gz"

Content-Type: application/x-gzip



H4sIAAAAAAAC/6tW8swrS80ryS+q9MksllGyUoiuVgrOLnXOT0kFcpQcXQ0MDIyVdJQcc3LykxNLMvPzgMIWFhY6SgGpRQWpJaWJOUABAx0lH6g0TGdKalpiaU6JUm1sLQCHcFtKZQAAAA==

--70834bf1-1439-4681-b1d4-fb3fa1f9efef--

解决方法

看起来您已经有了gzip压缩文件。如果是这样,当您使用getContents()时,您将收到一个base64结束编码的值。参见In NetSuite with SuiteScript 2.0 unable to send a file with HTTP POST request with a content-type multipart/form-data

您将需要以下内容:

body.push('Content-Type: application/x-gzip');
body.push('Content-Transfer-Encoding: base64');

实际上看起来您是根据该答案编写代码的。传输编码部分埋在注释中。