今天要做一個簡單的頁面,可以實現(xiàn)將文件 上傳到服務(wù)器(保存在指定文件夾)
#sample.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# coding:utf-8 from flask import flask,render_template,request,redirect,url_for from werkzeug.utils import secure_filename import os app = flask(__name__) @app .route( '/upload' , methods = [ 'post' , 'get' ]) def upload(): if request.method = = 'post' : f = request.files[ 'file' ] basepath = os.path.dirname(__file__) # 當(dāng)前文件所在路徑 upload_path = os.path.join(basepath, 'static\uploads' ,secure_filename(f.filename)) #注意:沒有的文件夾一定要先創(chuàng)建,不然會提示沒有該路徑 f.save(upload_path) return redirect(url_for( 'upload' )) return render_template( 'upload.html' ) if __name__ = = '__main__' : app.run(debug = true) |
#upload.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!doctype html> <html lang = "en" > <head> <meta charset = "utf-8" > <title>title< / title> < / head> <body> <h1>文件上傳示例< / h1> <form action = "" enctype = 'multipart/form-data' method = 'post' > < input type = "file" name = "file" > < input type = "submit" value = "上傳" > < / form> < / body> < / html> |
這里要注意:<form>標(biāo)簽里的enctype屬性一定要填寫'multipart/form-data'
意思是不加密,上傳文件的時候一定要選這個,不然不行
好了接下來我們看看運行效果
1. 初始界面
2. 選擇一個文件,點擊上傳
3. 最后網(wǎng)頁會回到初始界面,然后上傳的文件,也保存在我們指定的目錄上了
至此,項目結(jié)束@@
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/wongbingming/p/6802660.html