首页 > 解决方案 > Invoke-RestMethod 上传 ZIP 文件

问题描述

我尝试使用 POST 将文件上传到 uri。我不知何故失败了。我得到了帮助

powershell invoke-restmethod 多部分/表单数据

但他们上传了一个文本文件。

curl 命令也有效:

curl -X POST "https://some.place.over.the.rainbow.com/api/v1/dataupdate" -H "accept: */*" -H "Authorization: Basic 123123123123" -F "file=@/c/updates/SomeFile.zip"   

在我的 ps1 脚本中,我尝试了以下操作:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$Headers = @{
    Authorization = "Basic 123123123123"
};

$FilePath = "C:\Users\asd\SomeFile.zip";
$Uri = 'ttps://some.place.over.the.rainbow.com/api/v1/dataupdate';
$LF = "`r`n";
$boundary = [System.Guid]::NewGuid().ToString(); 

$fileBytes = [System.IO.File]::ReadAllBytes($FilePath);
$fileEnc = [System.Text.Encoding]::GetEncoding('UTF-8').GetString($fileBytes);

$bodyLines = ( 
    "--$boundary",
    "Content-Disposition: form-data; name=`"file`"; filename=`"SomeFile.zip`"",
    $fileEnc,
    "--$boundary--$LF" 
) -join $LF

Invoke-RestMethod -Uri $Uri -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Headers $Headers -Body $bodyLines

在服务器端我得到

Servlet.service() for servlet [dispatcherServlet] in context with path [/...] threw exception [Request processing failed; nested exception is
 org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; 
 nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: 
 Header section has more than 10240 bytes (maybe it is not properly terminated)] with root cause
 org.apache.tomcat.util.http.fileupload.MultipartStream$MalformedStreamException: Header section has more than 10240 bytes (maybe it is not properly terminated)at 
 org.apache.tomcat.util.http.fileupload.MultipartStream.readHeaders(MultipartStream.java:523) 
 ~[tomcat-embed-core-8.5.34.jar!/:8.5.34]at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:880) 
 ~[tomcat-embed-core-8.5.34.jar!/:8.5.34]at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:845) 

我需要在没有 curl 的 Windows 机器上执行它。

感谢任何帮助

标签: restpowershelluploadinvoke-command

解决方案


推荐阅读