python 让使用者上传档案,存在本地端,然后将页面导向档案url

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 让使用者上传档案,存在本地端,然后将页面导向档案url相关的知识,希望对你有一定的参考价值。

References
- Flask offical site: http://flask.pocoo.org/docs/0.12/patterns/fileuploads/

import os
from flask import Flask, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'uploaded_images'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    """Check whether a uploaded file is valid and allowed"""
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/uploads/<filename>')
def uploaded_file(filename):
    """generate url for user uploaded file"""
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)


@app.route('/image-test', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename) # security concerns
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

以上是关于python 让使用者上传档案,存在本地端,然后将页面导向档案url的主要内容,如果未能解决你的问题,请参考以下文章

python手机文件上传至电脑?

sourcetree如何将本地新项目上传到git(Mac端)

filezilla 不会用 复制请绕道

fastdfs档案伺服器,上传的档案存在哪

github 创建网络仓库 ,使用git工具将本地文件上传/删除 --- 心得

手机端其中一个模块使用html5来开发,如何实现用HTML5调用选择手机本地文件后上传。