'How can I download a file from a user-provided URL in Flask? [duplicate]

I want to get a URL from the user in my Flask application, then download and save that URL to disk.



Solution 1:[1]

Using requests, here's how to download and save the Google logo:

import requests

r = requests.get('https://www.google.com/images/srpr/logo11w.png')

with open('google_logo.png', 'wb') as f:
    f.write(r.content)

You can use this from within a Flask view to download a user provided URL.

from flask import request
import requests


@app.route('/user_download')
def user_download():
    url = request.args['url']  # user provides url in query string
    r = requests.get(url)

    # write to a file in the app's instance folder
    # come up with a better file name
    with app.open_instance_resource('downloaded_file', 'wb') as f:
        f.write(r.content)

Solution 2:[2]

I always use the following. It depends on the target file on how you process it, of course. In my case it is an icalender file.

from urllib.request import urlopen
//I used python3

location = 'http://ical.citesi.nl/?icalguid=81b4676a-b3c0-4b4c-89bd-d91c3a52fa7d&1511210388789'
result = urlopen(location)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Fthi.a.Abadi