How upload a photo to google drive using url of photo from VK or another social net

Viewed 124

I have a url of photo from VK. Here is that url:

https://sun9-28.userapi.com/impf/c850732/v850732336/16fa43/3b7pxN3vzmI.jpg?size=400x400&quality=96&sign=e43d16ae62020287b2e5ae9073d3f878&c_uniq_tag=5rB9bM19KvnvwLaYvsXilF2uT-MWISzsiNrvNJH65UQ&type=album

And i want to upload this image without downloading it to my computer. I did it before by using "requests". My code is below:

para = {'name': f'{name_photo}', 'parents': [folder_id]}
files = {'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
       # В запрос вставляем ссылку на фото в интернете и возвращаем в виде контента бинарного кода
       # потому что любой передаваемый файл должен быть в бинарном коде
'file': requests.get(url).content }
requests.post('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
                                headers={'Authorization': f'Bearer {access_token}'},
                                files=files)

And it works, but now i decided to use 'google drive api client' and i have a ploblem because i can't to upload the file. Here is my script

file_metadata = {'name': f'{name_photo}.jpg', 'parents': [folder_id]}
media = MediaFileUpload(url,
                        mimetype='image/jpeg')
service.files().create(body=file_metadata,
                       media_body=media,
                       fields='id').execute()

If i put in "MediaFileUpload" a local file, for example 'files/photo.jpg', i get success, but if i put the url i get an error

File "C:\Users\Sverchkov Family\Desktop\Моя учеба\Нетология\Python-разработчик\Basic python\Курсовая работа\Работа с доработаками и клиентской библиотекой гугл\lab_1_renew_by_google_client.py", line 128, in to_google_disk
    media = MediaFileUpload(url,
  File "C:\Users\Sverchkov Family\AppData\Local\Programs\Python\Python39\lib\site-packages\googleapiclient\_helpers.py", line 131, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\Sverchkov Family\AppData\Local\Programs\Python\Python39\lib\site-packages\googleapiclient\http.py", line 593, in __init__
    self._fd = open(self._filename, "rb")
OSError: [Errno 22] Invalid argument: 'https://sun9-28.userapi.com/impf/c850732/v850732336/16fa43/3b7pxN3vzmI.jpg?size=400x400&quality=96&sign=e43d16ae62020287b2e5ae9073d3f878&c_uniq_tag=5rB9bM19KvnvwLaYvsXilF2uT-MWISzsiNrvNJH65UQ&type=album'

I don't know how to fix this problem and upload the photo by url. Thanks if you help me

2 Answers

You cant pass a url to MediaFileUpload, you need to pass the file stream Download the file to your machine first then upload it to drive you cant go from a VK url to drive directly

string uploadedFileId;
// Create a new file on Google Drive
await using (var fsSource = new FileStream(UploadFileName, FileMode.Open, FileAccess.Read))
      {
      // Create a new file, with metadata and stream.
      var request = service.Files.Create(fileMetadata, fsSource, "text/plain");
      request.Fields = "*";
      var results = await request.UploadAsync(CancellationToken.None);

      if (results.Status == UploadStatus.Failed)
         {
         Console.WriteLine($"Error uploading file: {results.Exception.Message}");
         }

          // the file id of the new file we created
          uploadedFileId = request.ResponseBody?.Id;
      }

Code shamelessly ripped from How to upload a file to Google Drive with C# .net

You can try this approach which makes use of the MediaIoBaseUpload:

url = 'https://sun9-28.userapi.com/impf/c850732/v850732336/16fa43/3b7pxN3vzmI.jpg?size=400x400&quality=96&sign=e43d16ae62020287b2e5ae9073d3f878&c_uniq_tag=5rB9bM19KvnvwLaYvsXilF2uT-MWISzsiNrvNJH65UQ&type=album'
response = requests.get(url)
file_content = BytesIO(response.content) 
file_metadata = {'name': f'{name_photo}.jpg', 'parents': [folder_id]}
media = MediaIoBaseUpload(file_content, mimetype='image/jpeg')
service.files().create(body=file_metadata, media_body=media, fields='id').execute()

You will still have to use requests in order to retrieve the file content but you using the snippet above the upload will be done by using the Python API client library.

Reference

Related