Upload a file to Box.com using Powershell

巧了我就是萌 提交于 2019-12-05 10:57:20
John Hoerr

There are a couple things that make this a little tricky in PowerShell:

  1. The filename parameter specifies the name of the file, not the contents.
  2. A request body is required in order to specify the file name and destination.
  3. PowerShell treats -InFile and -Body arguments as mutually exclusive.
  4. PowerShell does not appear to natively support multipart/form-data POSTs, per the question that you referenced.

Since the request body is required (1,2) -- and thus -InFile can't be used (3) -- I think you might need to roll your own multipart/form-data body (4) that contains the necessary metadata and file content. This blog post describes a method for doing so. The content there is a short string (a tweet) but the principle is the same.

Below is a Fiddler trace of an upload I just performed using the Box Windows SDK. This shows how the request should look as it goes across the wire. The $BOUNDARY is an arbitrary, unique string -- a GUID works great.

POST https://upload.box.com/api/2.0/files/content HTTP/1.1
Authorization: Bearer $TOKEN
Content-Type: multipart/form-data; boundary="$BOUNDARY"
Host: upload.box.com
Content-Length: 2118
Accept-Encoding: gzip, deflate

--$BOUNDARY

Content-Disposition: form-data; name="file"; filename="$FILENAME"

<THE CONTENT OF $FILENAME>    

--$BOUNDARY

Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name="metadata"

{"parent":{"id":"$PARENT_FOLDER_ID"},"name":"$FILENAME"}

--$BOUNDARY--

Here is the response I received:

HTTP/1.1 201 Created
Date: Mon, 14 Apr 2014 12:52:33 GMT
Server: Apache
Cache-Control: no-cache, no-store
Content-Length: 364
Connection: close
Content-Type: application/json

{"total_count":1,"entries":[{"type":"file","id":"$ID","name":"$FILENAME", ... }]}

I may sound dumb, but what happens when you do this?

$body.Add("filename",  $([IO.File]::ReadAllBytes($SourcePath)))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!