FLASK實現上傳下載功能

來源:互聯網
上載者:User

標籤:cto   main   txt   style   html   abs   not   bsp   實現   

#!-*-coding=utf-8-*-# from flask import Flask## app = Flask(__name__)### @app.route(‘/‘)# def hello_world():#     return ‘Hello World!‘### if __name__ == ‘__main__‘:#     app.run()from werkzeug.utils import secure_filenamefrom flask import Flask,render_template,jsonify,request,send_from_directoryimport timeimport osimport base64app = Flask(__name__)UPLOAD_FOLDER=‘upload‘app.config[‘UPLOAD_FOLDER‘] = UPLOAD_FOLDERbasedir = os.path.abspath(os.path.dirname(__file__))ALLOWED_EXTENSIONS = set([‘txt‘,‘png‘,‘jpg‘,‘xls‘,‘JPG‘,‘PNG‘,‘xlsx‘,‘gif‘,‘GIF‘])# 用於判斷檔案尾碼def allowed_file(filename):    return ‘.‘ in filename and filename.rsplit(‘.‘,1)[1] in ALLOWED_EXTENSIONS# 用於測試上傳,稍後用到@app.route(‘/test/from‘)def upload_test():    return render_template(‘from.html‘)# 上傳檔案@app.route(‘/api/upload‘,methods=[‘POST‘],strict_slashes=False)def api_upload():    file_dir = os.path.join(basedir, app.config[‘UPLOAD_FOLDER‘])    if not os.path.exists(file_dir):        os.makedirs(file_dir)    f = request.files[‘myfile‘]  # 從表單的file欄位擷取檔案,myfile為該表單的name值    if f and allowed_file(f.filename):  # 判斷是否是允許上傳的檔案類型        fname = secure_filename(f.filename)        print fname        ext = fname.rsplit(‘.‘,1)[1]  # 擷取檔案尾碼        unix_time = int(time.time())        # new_filename = str(unix_time)+‘.‘+ext  # 修改了上傳的檔案名稱        new_filename = ‘12‘+‘.‘+ext  # 修改了上傳的檔案名稱        f.save(os.path.join(file_dir,new_filename))  #儲存檔案到upload目錄        token = base64.b64encode(new_filename)        print token        return jsonify({"errno":0, "errmsg":"上傳成功","token":token})    else:        return jsonify({"errno":1001, "errmsg":"上傳失敗"})@app.route(‘/api/load‘,methods=[‘GET‘])def load():    if request.method == "GET":        if os.path.isfile(os.path.join(‘upload‘, ‘12.jpg‘)):            return send_from_directory(‘upload‘, ‘12.jpg‘, as_attachment=True)        # abort(404)if __name__ == ‘__main__‘:    app.run(debug=True, port=9999)

官網:http://docs.jinkan.org/docs/flask/patterns/fileuploads.html

FLASK實現上傳下載功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.