首页 文章

在隐藏最终链接时下载保留原始文件名的文件

提问于
浏览
4

我需要下载一个文件,将其保存在文件夹中,同时保留网站上的原始文件名 .

url <- "http://www.seg-social.es/prdi00/idcplg?IdcService=GET_FILE&dID=187112&dDocName=197533&allowInterrupt=1"

在Web浏览器中,如果单击该链接,则可以下载具有以下文件名的excel文件:

AfiliadosMuni-02-2015.xlsx

我知道我可以使用R中的命令download.file轻松下载它,如下所示:

download.file(url, "test.xlsx", method = "curl")

但我真正需要的是我的脚本是下载它保持原始文件完整 . 我也知道我可以通过我的控制台卷曲这样做 .

curl -O -J $"http://www.seg-social.es/prdi00/idcplg?IdcService=GET_FILE&dID=187112&dDocName=197533&allowInterrupt=1"

但是,我再次在R脚本中需要这个 . 有没有类似于上面的方法,但在R?我已经研究过RCurl包但我找不到解决方案 .

2 回答

  • 9

    你总是可以这样做:

    library(httr)
    library(stringr)
    
    # alternate way to "download.file"
    fil <- GET("http://www.seg-social.es/prdi00/idcplg?IdcService=GET_FILE&dID=187112&dDocName=197533&allowInterrupt=1", 
               write_disk("tmp.fil"))
    # get what name the site suggests it shld be
    fname <- str_match(headers(fil)$`content-disposition`, "\"(.*)\"")[2]
    # rename
    file.rename("tmp.fil", fname)
    
  • 0

    我认为 basename() 将是最简单的选择https://www.rdocumentation.org/packages/base/versions/3.4.3/topics/basename

    例如

    download.file(url, basename(url))

相关问题