Flask同时上传图像和文本

时间:2018-06-15 02:03:14

标签: flask

所以我想在这里实现的是同时上传和图像和文本。到目前为止它已经奏效,但在Flask上,request.files是空的。但是,request.form会将此返回给我:

ImmutableMultiDict([('description', u''), ('name', u''), ('file', u'image.jpg')])

当我type(request.form['file'])时,它返回unicode。我如何制作这样的图片,以便request.files上的图片和request.form上的文字

<form class="form-area " id="" action="{{ url_for('templater.test') }}" method="post"  novalidate>
							
  <label for="name">Name</label>
  <input name="name" placeholder="Enter Name" type="text">

  <label for="description">Description</label>
  <input name="description" placeholder="Enter Description" type="text">

  
  <input type = "file" name = "file" />

  <input type = "submit"/>
</form>

@templater.route('/test', methods=['GET', 'POST'])
def test():
    print request.form
    if request.method == 'POST':

        if 'file' not in request.form:
            print 'No file part'
            return redirect(request.url)
        file = request.form['file']

        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(main.app.config['UPLOAD_FOLDER'], filename))

    return jsonify({'status':'something'})

1 个答案:

答案 0 :(得分:1)

您应该在表单标记中指定enctype属性:

<form class="form-area " id="" action="{{ url_for('templater.test') }}" method="post"  novalidate  enctype="multipart/form-data">

通过添加,您应该能够调用文件

 files = request.files.getlist('file')
 for file in files:
     [...]

其他输入仍以表格形式提供:

request.form.get('name')