PepsiCo
PepsiCo

Reputation: 1409

How to download file from internet via R

I have an url, and I want to download the file via R, I notice that download.file would be helpful, but my problem seems different:

url <- "http://journal.gucas.ac.cn/CN/article/downloadArticleFile.do?attachType=PDF&id=11771"
destfile <- "myfile.pdf"
download.file(url, destfile)

It doesn't work! I notice that if my url is in the form of xxx.pdf, then the code above is no problem, otherwise the file that is downloaded is corrupt.

Does anyone know how to solve this problem?

Upvotes: 6

Views: 11642

Answers (2)

Saber Aradpour
Saber Aradpour

Reputation: 9

I am trying to download an nc file with R. It downloads well but I get this error when trying to open it:

Error in R_nc4_open: NetCDF: Unknown file format Error in nc_open("SM_D2010323_Map_SATSSS_data_1day.nc") : Error in nc_open trying to open file SM_D2010323_Map_SATSSS_data_1day.nc (return_on_error= FALSE )

url <- "https://www.star.nesdis.noaa.gov/data/socd1/coastwatch/products/miras/nc/SM_D2010323_Map_SATSSS_data_1day.nc"
destfile <- "***/SM_D2010323_Map_SATSSS_data_1day.nc"
download.file(url, destfile)
nc_data <- nc_open('SM_D2010323_Map_SATSSS_data_1day.nc')

But when I use the same URL on my web browser, I can open the file without any problems with R.

Upvotes: -2

Troy
Troy

Reputation: 8691

Setting the mode might be required to treat the file as binary data while saving it. If I leave that argument out, I get a blank file, but this way works for me:

url <- "http://journal.gucas.ac.cn/CN/article/downloadArticleFile.do?
attachType=PDF&id=11771"
destfile <- "myfile.pdf"
download.file(url, destfile, mode="wb")

Upvotes: 10

Related Questions