溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python3 flask實(shí)現(xiàn)文件上傳功能

發(fā)布時(shí)間:2020-08-20 13:59:21 來源:腳本之家 閱讀:139 作者:diyiday 欄目:開發(fā)技術(shù)

本文實(shí)例為大家分享了python3-flask文件上傳操作的具體代碼,供大家參考,具體內(nèi)容如下

# -*- coding: utf-8 -*-
import os
import uuid
import platform
from flask import Flask,request,redirect,url_for
from werkzeug.utils import secure_filename

if platform.system() == "Windows":
 slash = '\\'
else:
 platform.system()=="Linux"
 slash = '/'
UPLOAD_FOLDER = 'upload'
ALLOW_EXTENSIONS = set(['html', 'htm', 'doc', 'docx', 'mht', 'pdf'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#判斷文件夾是否存在,如果不存在則創(chuàng)建
if not os.path.exists(UPLOAD_FOLDER):
 os.makedirs(UPLOAD_FOLDER)
else:
 pass
# 判斷文件后綴是否在列表中
def allowed_file(filename):
 return '.' in filename and \
   filename.rsplit('.', 1)[1] in ALLOW_EXTENSIONS

@app.route('/',methods=['GET','POST'])
def upload_file():
 if request.method =='POST':
  #獲取post過來的文件名稱,從name=file參數(shù)中獲取
  file = request.files['file']
  if file and allowed_file(file.filename):
   # secure_filename方法會(huì)去掉文件名中的中文
   filename = secure_filename(file.filename)
   #因?yàn)樯洗蔚奈募赡苡兄孛虼耸褂胾uid保存文件
   file_name = str(uuid.uuid4()) + '.' + filename.rsplit('.', 1)[1]
   file.save(os.path.join(app.config['UPLOAD_FOLDER'],file_name))
   base_path = os.getcwd()
   file_path = base_path + slash + app.config['UPLOAD_FOLDER'] + slash + file_name
   print(file_path)
   return redirect(url_for('upload_file',filename = file_name))
 return '''
 <!doctype html>
 <title>Upload new File</title>
 <h2>Upload new File</h2>
 <form action="" method=post enctype=multipart/form-data>
  <p><input type=file name=file>
   <input type=submit value=Upload>
 </form>
 '''
if __name__ == "__main__":
 app.run(host='0.0.0.0',port=5000)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI