The form file upload flask

In the form upload file must be added enctype = "multipart / form-data" attribute

Why join this property it:

enctype is encodetype is the type of encoding means.

multipart / form-data refers to form a plurality of data parts, meaning both text data, binary data files there.

Note that: By default, the value of enctype is application / x-www-form-urlencoded, can not be used for file uploads, only use the multipart / form-data, in order to complete the transfer file data.

application / x-www-form-urlencoded can only upload files in text format, and multipart / form-data is about to upload files in binary form, you can achieve multiple file upload

Usually the uploaded data may be acquired request.form [], [] attribute name fill

Acquired form to upload a file in the view function can be used request.file.get () method, get to fill in the name attribute

And upload files to a specified folder, there are several ways

I was using it: File .save (file path)

Database table and view function model as follows:

class Users(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(48), unique=True)
sex = db.Column(db.String(12))
pic = db.Column(db.String(48))

app.route @ ( '/ index /', Methods = [ 'the GET', 'the POST']) 
DEF index ():
IF request.method == 'the GET':
return the render_template ( 'index.html')
IF Request. == Method 'the POST':
     # uploaded files and data acquired
iconsThe = request.files.get ( 'iconsThe')
name = Request.Form [ 'name']
Sex = Request.Form [ 'Sex']
# Upload specified path
= UPLOAD_DIC 'static / Upload'
# splice file full path
file_path = the os.path.join (UPLOAD_DIC, icons.filename)
# upload files to the specified path
icons.save (file_path)
User = the Users (name = name, Sex = Sex, file_path = PIC)
db.session.add (User)
db.session.the commit ()
MSG = 'upload success'
return render_template ( 'index.html', msg = msg, pic = file_path)
Template follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传图片</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" >
{% if pic %}
<div >
<img style="width: 200px;height: 100px" src="/{{ pic }}/ " alt="">
</div>
{% endif %}
<label for="name">姓名</label>
<input type="text" id="name" name="name">
<label for="sex"></label>
<br>
男<input type="radio" name="sex" id="sex" value="男">
女<input type="radio" name="sex" id="sex" value="女">
<br>
<input type="file" name="icons">
<br>
<input type="submit" value="提交">
</form>
</body>
</html>

Guess you like

Origin www.cnblogs.com/Jokerguigui/p/11535196.html