fileUpload/main.py


Home Back

#!/usr/bin/env python3
import  os,urllib3,time
from bottle import Bottle,route, run, template, static_file, request,redirect, response,get, post



#Edit if you want

SAVEPATH=os.getcwd()
SHAREPATH=os.getcwd()
YOURNAME="Fabio Di Matteo"
PORT=5500

#Not edit
WEBURL=''
ip=''


app=Bottle()

def start_server():
    run(app , host='0.0.0.0', port=PORT, reloader=True)
    #import bjoern
    #bjoern.run(app, "0.0.0.0", PORT)

@app.route('/js/<filename>')
def send_js(filename):
    return static_file(filename, root=os.path.dirname(os.path.realpath(__file__))+'/tpl/js/')
 
@app.route('/css/<filename>')
def send_css(filename):
    return static_file(filename, root=os.path.dirname(os.path.realpath(__file__))+'/tpl/css/')
 
@app.route('/img/<filename>')
def send_img(filename):
    return static_file(filename, root=os.path.dirname(os.path.realpath(__file__))+'/tpl/img/')

@app.route ("/")
def home():
    homepage=open(os.path.dirname(os.path.realpath(__file__))+"/tpl/uploadForm.html").read()
    yield template(homepage,yourname=YOURNAME)


@app.route('/share')
def homeshare():
    redirect("/share/")

@app.route('/share/')
def fromRootShare():
    
    getWebUrl()
    parentDir='#'
    currDir='/share/'
    
    line=''
    flist = os.listdir(SHAREPATH+os.sep)
    for i in range(len(flist)):
        if  os.path.isdir(SHAREPATH+os.sep+os.sep+flist[i]):
            img='folder.png'
            line=line + '<li class="list-group-item"><a href="{f}"><img style="width: 30px;margin-right:10px" src="/img/{img}"/>{onlyFileName}</a></li>'.format(f=flist[i],onlyFileName=flist[i],WEBURL=WEBURL, img=img );
    for i in range(len(flist)):
        if  not os.path.isdir(SHAREPATH+os.sep+os.sep+flist[i]):
            img='file.png'
            
            webroot=getWebUrl()+"share/"
            
            file_size = os.path.getsize(SHAREPATH+os.sep+os.sep+flist[i])
            modDate=time.strftime("%d/%m/%Y %H:%M:%S",time.localtime(os.path.getmtime(SHAREPATH+os.sep+os.sep+flist[i])))
            line=line + '<li class="list-group-item"><a target="_blank" href="{f}">\
            <img style="width: 30px;margin-right:10px" src="/img/{img}"/>{onlyFileName}</a>\
            <span style="color:#4D4D4D;font-size:11px;float:right;" >{file_size} bytes - {modDate}</span></li>\
            '.format(f=webroot+flist[i],onlyFileName=flist[i], img=img, modDate=modDate, file_size=file_size );
            
    page=open(os.path.dirname(os.path.realpath(__file__))+"/tpl/share.html").read()
    page=page.format(line=line, WEBURL=WEBURL, parentDir=parentDir,currDir=currDir)
    return page



@app.route('/share/<filename:path>')
def send_file(filename):
    line=''
    getWebUrl()
    parentDir=os.path.dirname(WEBURL+'share/'+filename)
    
    
    if not os.path.isdir(SHAREPATH+os.sep+filename):
        return static_file(filename, SHAREPATH)
    else:
        flist = os.listdir(SHAREPATH+os.sep+filename)
        currDir='/share/'+filename
        for i in range(len(flist)):
            if  os.path.isdir(SHAREPATH+os.sep+filename+os.sep+flist[i]):
                img='folder.png'
                
                line=line + '<li class="list-group-item"><a href="{WEBURL}share/{f}"><img style="width: 30px;margin-right:10px" src="{WEBURL}img/{img}"/>{onlyFileName}</a></li>'.format(f=filename+os.sep+flist[i],onlyFileName=flist[i],WEBURL=WEBURL, img=img );
        
        for i in range(len(flist)):
            if not os.path.isdir(SHAREPATH+os.sep+filename+os.sep+flist[i]):        
                img='file.png'
                file_size = os.path.getsize(SHAREPATH+os.sep+filename+os.sep+flist[i])
                modDate=time.strftime("%d/%m/%Y %H:%M:%S",time.localtime(os.path.getmtime(SHAREPATH+os.sep+filename+os.sep+flist[i])))
                line=line + '<li class="list-group-item"><a href="{WEBURL}share/{f}"><img style="width: 30px;margin-right:10px" src="{WEBURL}img/{img}"/>{onlyFileName}</a><span style="color:#4D4D4D;font-size:11px;float:right;" >{file_size} bytes - {modDate}</span></li>'.format(f=filename+os.sep+flist[i],onlyFileName=flist[i],WEBURL=WEBURL, img=img,modDate=modDate,file_size=file_size );
        
        
    
    page=open(os.path.dirname(os.path.realpath(__file__))+"/tpl/share.html").read()
    page=page.format(line=line, WEBURL=WEBURL, parentDir=parentDir,currDir=currDir)
    return page



        
    


def getPublicIpRaw():
    url = "https://www.freemedialab.org/myip/rawip.php"
    http = urllib3.PoolManager()
    try:
        r = http.request('GET', url)
        return r.data.decode('utf-8')
    except :
        return '127.0.0.1'
        


@app.error(404)  
def error404(error):
    return '''
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Invia a Fabio Di Matteo</title>
        <meta http-equiv="content-type" content="text/html;charset=utf-8" />
        <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <script src="/js/jquery.min.js"></script>
        <link rel="stylesheet" href="/css/bootstrap.min.css">
        <script src="/js/bootstrap.bundle.min.js"></script>
        </head>
    <body>
    <div class="container" class="mt-3">
        <div class="jumbotron">
          <h1 class="display-4">La pagina che stai cercando non esiste!</h1>
          <p class="lead">Smettila di andare in giro per il server.</p>
          <hr class="my-4">
          <p>Questo è un server temporaneo. Fra poco %s lo spegne.</p>
          <p class="lead">
            <a class="btn btn-primary btn-lg btn-success" href="/" role="button">Ritorna alla home</a>
          </p>
        </div>
    </div> 
    </body>
    </html>
    ''' % YOURNAME



@app.route('/error')
def error():
    c='<div class="alert alert-danger" role="alert">Qualcosa è andato storto nell\' invio del file.</div>'
    yield(c)

@app.route('/success')
def success():
    c='<div class="alert alert-success" role="alert">I file sono stati inviati correttamente.</div>'
    yield(c)

'''
#upload singolo file

@app.route('/upload',method='POST')
def upload():
    myfile = request.files.myfile
    save_path = os.path.join(SAVEPATH, myfile.filename)
    
    myfile.save(save_path, overwrite=True)
    print('File salvato correttamente.')
    redirect("/success")
'''
    
@app.route('/upload',method='POST')
def upload():
    myfiles = request.files.getall('myfile')
    for myfile in myfiles:
        save_path = os.path.join(SAVEPATH, myfile.filename)
        myfile.save(save_path, overwrite=True)

    redirect("/success")


def getWebUrl():
    global WEBURL
    scheme = request.urlparts.scheme
    netloc = request.urlparts.netloc
    WEBURL="{scheme}://{host}/".format(scheme=scheme,host=netloc)
    print("WEBURL: %s" % WEBURL)
    return WEBURL

if __name__=='__main__': 
    ip=getPublicIpRaw()
    
    
    print("---------------------------------------------")
    print("\nIl Tuo ip: http://%s:%s\n\n" % (ip,PORT))
    print("---------------------------------------------")
    
    start_server()    

Powered by Code, a simple repository browser by Fabio Di Matteo