1

I'm wondering if it's possible to use ajax to upload an image to a flask server in request.files by typing in the url through a form. Here is my current form setup:

<form method=post enctype=multipart/form-data runat="server" id="capture_form">
<div class="form-group">
        <label for=facesURL>URL:</label>
        <input type="text" name="image_url" class="form-control" id=facesURL placeholder="URL of image">
        <input type="submit" value="Preview URL image" id="submit">
</div>
<button align="center" class="btn btn-info upload-image" id=upload-image type=submit value="Upload Image">Upload File</button>

At the moment, the preview URL image button displays the image from the url into an , however I'm stuck at actually grabbing that src and uploading it on click of the upload image button. Any help is appreciated.

Matt S
  • 23
  • 1
  • 6

1 Answers1

0

If the user is specifying a URL, it may make more sense to have the server download the image from the specified URL itself (on the back-end) rather than trying to have the webpage download and send the image directly.

Here's a rough (untested) view function that shows what your code may end up looking like:

@app.route('/submit_image', methods=['GET', 'POST'])
def submit_image():
    # I'm assuming you're using the Flask-WTF module for your forms
    form = SubmitImageForm()
    if request.method == 'GET':
        return render_template('submit_image.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            path_to_save_image_to = ''  # Fill this in

            with open(path_to_save_image_to,'wb') as f:
                f.write(urllib.request.urlopen(form.image_url.data, path_to_save_to).read())

            return redirect(url_for('submission_successful'))
        else:
            return render_template('submit_image.html', form=form, error="Invalid submission")

With help from: Downloading a picture via urllib and python

Nathan Wailes
  • 9,872
  • 7
  • 57
  • 95
  • I'm not exactly sure what the Flask_WTF module is, i'm just sending the file over through html at the moment. so will form.image_url.data contain the equivalent of the request.files['file'] if using this SubmitImageForm function? – Matt S Jul 07 '17 at 15:29
  • `SubmitImageForm` is actually a user-defined class, not a function. You can create such classes when using flask_wtf. [I believe](https://stackoverflow.com/a/16664376/4115031) the equivalent of `form.image_url.data` when not using flask_wtf would be `request.form['image_url']`, assuming you named the field 'image_url'. – Nathan Wailes Jul 07 '17 at 15:35