-1

I am trying to build a file upload algorithm in flask using flask_wtf for handling upload form. My question is how do I get the mimetype of the input file.


class FileUploadForm(FlaskForm):
    file = FileField('File', validators=[DataRequired(), Length(min=1)])
    submit = SubmitField('Upload')

@blueprint.route('/upload/', methods=['GET', 'POST'])
def upload():
    form = FileUploadForm()
    if form.validate_on_submit():
        new_file = File(secure_filename(form.file.name), 
                         form.file.read()
                          mimetype=# HERE I NEED TO PASS THE MIMETYPE)
        db.session.add(new_file)
        db.session.commit()
        flash('File uploaded successfully !', 'success')
        return redirect(url_for('view', file_id=new_file.id))
    return render_template('files/upload.html', title='Upload Files')

rajatomar788
  • 339
  • 3
  • 9
  • Does this answer your question? [How to find the mime type of a file in python?](https://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python) – Sayse Jan 06 '20 at 10:45
  • No, the question is how do I access the content_type attribute of request from FlaskForm object. – rajatomar788 Jan 06 '20 at 10:51
  • Does this answer your question? [Flask / Python. Get mimetype from uploaded file](https://stackoverflow.com/questions/3447883/flask-python-get-mimetype-from-uploaded-file) – CDJB Jan 06 '20 at 12:59

1 Answers1

0

Okay I got it. Here is the code for people wanting it.



class FileUploadForm(FlaskForm):
    file = FileField('Choose File', validators=[FileRequired()])
    submit = SubmitField('Upload')


@blueprint.route('/upload/', methods=['GET', 'POST'])
def upload():
    form = FileUploadForm()
    if form.validate_on_submit():
        secure_name = secure_filename(form.file.data.filename)
        new_file = File(secure_name, form.file.data.stream.read(),
                        mime_type=form.file.data.mimetype,
                        length=form.file.data.stream.tell())
        db.session.add(new_file)
        db.session.commit()
        flash('File uploaded successfully !', 'success')
        return redirect(url_for('manager.files.view', file_id=new_file.id))
    return render_template('files/upload.html', form=form, title='Upload Files')


rajatomar788
  • 339
  • 3
  • 9