Friday, May 5, 2017

simple fileuplad / index using flask

**** file structure ********
├── templates
│   └── upload.html
├── upload

*** code *******
from flask import render_template
from flask import Flask, request, redirect, url_for, send_from_directory
import os
from flask.ext.autoindex import AutoIndex
app = Flask(__name__)
AutoIndex(app, browse_root=os.path.curdir)

ufolder = "./upload"
app.config['Udir'] = ufolder
app.config['Fdir'] = 'files'

@app.route('/uploader', methods=['GET', 'POST'])
def uploader():
    state = "welcome"
    if request.method == 'POST':
        # check if the post request has the file part
        print request.files
        if 'fileToUpload' not in request.files:
            # flash('No file part')
            state = 'nofile'
            return render_template('./upload.html', state=state)
        fileu = request.files['fileToUpload']
        # if user does not select file, browser also
        # submit a empty part without filename
        if fileu.filename == '':
            # flash('No selected file')
            state = 'nofile'
            return render_template('./upload.html', state=state)
        # if fileu and allowed_file(fileu.filename):
            filename = fileu.filename
            # filename = secure_filename(fileu.filename)
  ['Udir'], filename))
            # return redirect(url_for('uploaded_file',
                                    # filename=filename))
            state = 'uploaded'
            return render_template('./upload.html', state=state)

        return render_template('./upload.html', state=state)

if __name__ == "__main__":

*** upload.html code ******
    <! DOCTYPE html>
    <form  method="post" action="/uploader" enctype="multipart/form-data">
        {{ state }}
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">

1- to run it we can use
$ python
it will listen to only localhost, port 5000

if you want it to listen on all interface run the following command

$ export

$ python -m flask run --host=

2- to access use the following url
will get directory index

will get you a upload form, and the file will be uploaded to folder upload.

No comments:

Post a Comment