首页 > 解决方案 > 为什么 `download.file()` 从有效的公共 Dropbox 链接下载损坏的文件?

问题描述

编辑:所以我设法让其他东西工作(包括在下面)。但我仍然想了解为什么我的第一次尝试没有成功。

这是我尝试使用 download.file 下载我的公开可用的 Dropbox 文件:

library("readxl")

# Define public download link location ------------------------------------------
excelUrl = "https://www.dropbox.com/s/v9lm9y7nso8yw1x/dashboardTotals.xlsx?dl=1"
     # I've experimented with appending '&raw=1' to this, doesn't seem to do anything.

# Function for downloading .xlsx into current wd --------------------------------
read_url_excel <- function(url,saveas = paste0(getwd(),"/newExcelFile.xlsx")){
  download.file(url, destfile = saveas)
  url_excel <- readxl::read_excel(saveas)
  return(url_excel)
}

# This doesn't work, because the file is corrupted and can't be read by read_excel()
excelTable = read_url_excel(excelUrl)
#> Error: Evaluation error: error reading from the connection.

reprex 包于 2020-01-09 创建(v0.3.0)

你可能会说我不太确定连接/文件在 R 中是如何工作的。我已经设法让它工作了:

excelUrl = "https://www.dropbox.com/s/v9lm9y7nso8yw1x/dashboardTotals.xlsx?dl=1&raw=1"

tmpF <- paste0(getwd(),"/newTing.xlsx")
theFile <- url(excelUrl, open="rb")

binary = readBin(theFile,raw(),100000)

writeBin(binary,tmpF)

reprex 包于 2020-01-09 创建(v0.3.0)

为什么方法1失败,方法2成功?

标签: rdownloaddropboxreadxl

解决方案


推荐阅读