我正尝试通过API调用将Excel作为附件上传,该API调用需要Excel文件的base64编码版本。通过API成功上传了该文件,但下载时Excel显示一条消息,指出该文件已损坏,无法打开。
我已经尝试了各种不同的payload输出调整。我完全按照API参考文档的要求,文件成功上传。我希望文件应该能够在上传后下载并打开,但我得到了一个损坏的文件。下面是成功上传文件的代码,但似乎没有正确编码文件:
下面是我成功上传文件的现有代码。Payload结构基于API文档:
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")
1条答案
按热度按时间sczxawaw1#
您不需要阅读文件。您可以执行以下操作: