繁体   English   中英

Powershell:如何在多部分/表单数据请求中发布 excel (.xlsx) 文件?

[英]Powershell: How can I POST excel (.xlsx) files in a multipart/form-data request?

我正在尝试使用 Multer 作为文件上传中间件将一些数据发布到 Express 服务器。

该请求包括几个文本字段、一个 API (.yaml) 文件和一个.xlsx 文件。 我可以成功发布 .yaml 文件和文本字段,但不能成功发布 excel 文件。

下面是我如何构建 multipart/form-data 调用:

# ----- BUILD & EXECUTE API CALL ------

# Set up the boundary, separator and file encoding to use
$boundary = [System.Guid]::NewGuid().ToString() 
$LF = "`r`n"
$enc = [System.Text.Encoding]::GetEncoding("iso-8859-1")

# Get the filename of the .yaml file
$apiFileName = Split-Path $apiFilePath -leaf

# Encode the .yaml file contents
$apiDefBin = [IO.File]::ReadAllBytes("$apiFilePath")
$apiDefEnc = $enc.GetString($apiDefBin)

# Get the filename of the .xlsx file
$excelFileName = Split-Path $excelFilePath -leaf

# Encode the .xlsx file contents
$excelBin = [IO.File]::ReadAllBytes("$excelFilePath")
$excelEnc = $enc.GetString($excelBin)

# Build the body of the multipart request
$bodyLines = (
  "--$boundary",
  'Content-Disposition: form-data; name="textField"',
  '',
  "$textField",
  "--$boundary",
  "Content-Disposition: form-data; name=`"apiDef`"; filename=`"$apiFileName`"",
  'Content-Type: application/octet-stream',
  $apiDefEnc,
  "--$boundary--",
  "Content-Disposition: form-data; name=`"excelFile`"; filename=`"$excelFileName`"",
  'Content-Type: application/octet-stream',
  $excelFileEnc,
  "--$boundary--"
) -join $LF

# Execute the call
Invoke-WebRequest $url `
  -Verbose `
  -Method Post `
  -TimeoutSec 60 `
  -ContentType "multipart/form-data; boundary=$boundary" `
  -Body $bodylines

该请求似乎成功:

我正在服务器上打印req.bodyreq.files ,以查看发布的内容:

{ textField: 'some text here' }
{ apiDef:
   [ { fieldname: 'apiDef',
       originalname: 'api-def.yaml',
       encoding: '7bit',
       mimetype: 'application/octet-stream',
       destination: 'temp',
       filename: 'api-def.yaml',
       path: 'temp\\api-def.yaml',
       size: 2276 } ] }

所以.yaml文件成功发布,文本字段也是如此。 但是,没有发送 excel 文件。

我尝试更改内容类型,并研究是否应该使用另一种编码,但无济于事。

我正在尝试做的事情可能吗? 我究竟做错了什么?

尝试在上传 xlsx 文件之前在上一行中的边界之后取出两个破折号?

$apiDefEnc, "--$boundary--", <----- THIS BIT "Content-Disposition: form-data; name= "excelFile "; filename= "$excelFileName "", 'Content-Type: application /八位流',

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM