2017-07-07 64 views
1

我想知道是否有可能通过在表单中​​输入url来使用ajax将图像上传到flask.server文件服务器中。这是我目前的形式设置:上传图像文件到服务器给定的URL

<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> 

目前,预览URL图像按钮从网址到显示图像,但我被困在实际上抓住那个src和上传的上传点击图像按钮。任何帮助表示赞赏。

回答

0

如果用户指定一个URL,让服务器从指定的URL本身(在后端)下载图像可能更有意义,而不是试图让网页下载并直接发送图像。

这里有一个粗略的(未经测试)取景功能,显示你的代码,最终可能看起来像:

@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") 

的帮助来自:Downloading a picture via urllib and python

+0

我不能完全肯定Flask_WTF模块是什么,我现在只是通过html发送文件。那么如果使用这个SubmitImageForm函数,form.image_url.data将包含request.files ['file']的等价物吗? –

+0

'SubmitImageForm'实际上是一个用户定义的类,而不是一个函数。使用flask_wtf时可以创建这样的类。 [我相信](https://stackoverflow.com/a/16664376/4115031)当不使用flask_wtf时,相当于'form.image_url.data'会是'request.form ['image_url']',假设你命名为字段'image_url'。 –