I am trying to upload an Excel as an attachment via an API call that requires a base64 encoded version of the Excel file. The file is uploaded successfully via the API, but when downloaded Excel shows a message that the file is corrupted and cannot be opened.
I have tried various different tweaks to the payload output. I am following exactly what the API reference documentation asks for and the file is uploading successfully. I expect that the file should be able to be downloaded and opened after upload, but am getting a corrupted file. Here is the code that successfully uploads the file, but does not seem to be properly encoding the file:
Here is my existing code that successfully uploads the file. The Payload structure is based on the API documentation:
url <- <api_url>
# Read the contents of the Excel file as a raw object
excel_file_raw <- readBin(excel_file_path, what = "raw", n =file.info(excel_file_path)$size)
# Encode the Excel file as a base64 string
file_64_content <- base64enc::dataURI(excel_file_raw,paste0("application/vnd.openxmlformats- officedocument.spreadsheetml.sheet;name=",file_name), encoding = "base64")
# Define boundary string
boundary_string <- "-----boundary"
# Create payload
payload <- paste0("--", boundary_string,
"\r\nContent-Disposition: form-data; name=\"file\"; filename=\"", file_name, "\"",
"\r\n\r\n",file_64_content,
"\r\n--", boundary_string,
"\r\nContent-Disposition: form-data; name=\"parent\"",
"\r\n\r\n", task_id,
"\r\n--", boundary_string,
"\r\nContent-Disposition: form-data; name=\"resource_subtype\"",
"\r\n\r\nattachment",
"\r\n--", boundary_string, "--\r\n")
# Send POST request
response <- httr::POST(url,
body = payload,
add_headers('authorization' = paste0("Bearer ", api_token),
'content-type' = paste0("multipart/form-data; boundary=", boundary_string),
'accept' = 'application/json'),
encode = "multipart")
# Check API response
content(response, "text")