如何正确使用 Base64 编码 Excel 文件以通过 API 上传

问题描述 投票:0回答:1

我正在尝试通过 API 调用将 Excel 作为附件上传,该调用需要 Excel 文件的 base64 编码版本。 文件已通过 API 成功上传,但下载后 Excel 会显示文件已损坏且无法打开的消息。

我尝试了对有效负载输出进行各种不同的调整。我完全按照 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")
r shiny base64 attachment
1个回答
0
投票

您不需要阅读该文件。你可以这样做:

dataURI(file = path_to_xlsx_file, mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
© www.soinside.com 2019 - 2024. All rights reserved.