Hi everyone
I have written PowerShell script to upload different files to needed folders in Box
API call return normal response and the files appear in box, but just txt files have content. PDF are empty and for other files just download button. After download the files are broken.
Request body contains boundary and the content of file gotten using StremReader.
For each file type I sent its own Content-Type selected by extension.
$fileName = (Get-Item $filePath).Name
# Determine the content type based on file extension
$contentType = Get-ContentType $filePath
$line = '{"name":"' + $fileName + '", "parent":{"id":"' + $parentId + '"}}'
# Open a FileStream to read the file content
$fileStream = [System.IO.File]::OpenRead($filePath)
# Create a stream reader to read the file content
$streamReader = [System.IO.StreamReader]::new($fileStream)
$fileContent = $streamReader.ReadToEnd()
# Create the boundaries for the multipart/form-data request
$boundary = "------------------------" + [System.Guid]::NewGuid().ToString()
# Build the request body
$body = (
"--$boundary",
'Content-Disposition: form-data; name="attributes"',
'',
$line,
"--$boundary",
"Content-Disposition: form-data; name='file'; filename='$fileName'",
"Content-Type: $contentType",
"",
$fileContent,
"--$boundary--"
) -join "`r`n"
# Make the API request to upload the file
$response = Invoke-RestMethod -Uri $uploadUrl -Method Post -Headers $headers -ContentType "multipart/form-data; boundary=$boundary" -Body $body
uploadUrl “https://upload.box.com/api/2.0/files/content”
function with content types
function Get-ContentType {
param (
string]$filePath
)
$extension = nSystem.IO.Path]::GetExtension($filePath).ToLower()
switch ($extension) {
".txt" { return "text/plain" }
".pdf" { return "application/pdf" }
".doc" { return "application/msword" }
".docx" { return "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }
".xls" { return "application/vnd.ms-excel" }
".xlsx" { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }
default { return "application/octet-stream" }
}
}
I understand that the problem is where I get content or encode it, I tried different ways, something like this
$fileStream = mSystem.IO.File]::OpenRead($filePath) # Create a stream reader to read the file content
$streamReader = rSystem.IO.StreamReader]::new($fileStream, aSystem.Text.Encoding]::UTF8)
$fileContent = $streamReader.ReadToEnd()
But still small progress. The files I am uploading are a small files, nothing extraordinary, they something like samples.