英文:
How to get mimetype of the input file in a form using FlaskForm?
问题
我正在尝试使用Flask和flask_wtf构建文件上传算法来处理上传表单。我的问题是如何获取输入文件的MIME类型。
class FileUploadForm(FlaskForm):
file = FileField('文件', validators=[DataRequired(), Length(min=1)])
submit = SubmitField('上传')
@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=# 在这里我需要传递MIME类型)
db.session.add(new_file)
db.session.commit()
flash('文件上传成功!', 'success')
return redirect(url_for('view', file_id=new_file.id))
return render_template('files/upload.html', title='上传文件')
注意:在代码中的"mimetype=# 在这里我需要传递MIME类型"部分,你需要补充获取MIME类型的代码。获取MIME类型的方法通常是使用Python的mimetypes
模块或通过检查文件扩展名来推断。
英文:
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')
答案1
得分: 0
class FileUploadForm(FlaskForm):
file = FileField('选择文件', validators=[FileRequired()])
submit = SubmitField('上传')
@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('文件上传成功!', 'success')
return redirect(url_for('manager.files.view', file_id=new_file.id))
return render_template('files/upload.html', form=form, title='上传文件')
英文:
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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论