1. 程式人生 > >flask-圖片回顯-圖片下載

flask-圖片回顯-圖片下載

import uuid
from flask import send_from_directory,url_for
@app.route('/mulfileupload/',methods=['GET','POST'])
def mulfileupload():
    if request.method=='POST':
        files=request.files.getlist('wenjian')
        filelist=[]
        urllist=[]
        for file in files:
            filename=file.filename
            filetype=filename.split('.')[-1]
            print(filename)
            print(filetype)
            uploadpath=os.getcwd()+os.sep+'static/file'
            if not os.path.exists(uploadpath):
                os.mkdir(uploadpath)
            filename=str(uuid.uuid1())+'.'+filetype
            print(filename)
            file.save(uploadpath+os.sep+filename)
            filelist.append(filename)
            #照片回顯url
            url = url_for("static", filename="file/" + filename)
            urllist.append(url)

        return render_template('ceshi.html',msg='檔案上傳成功',filelist=filelist,urllist=urllist)
    else:
        return render_template('ceshi.html')

@app.route('/down/<filename>/')
def down(filename):
    dir=os.getcwd()+os.sep+'static/file/'
    print(dir+filename)
    #下載圖片設定
    return send_from_directory(dir,filename,as_attachment=True)
<form action="/mulfileupload/" method="post" enctype="multipart/form-data">
    <input type="file" name="wenjian" multiple=""><button type="submit">上傳</button>
</form>{{ msg }}

{% if filelist %}
<p>檔案列表</p>

    {% for fn in filelist %}

    <p><a href="/down/{{ fn }}/">{{ fn }}</a></p>

    {% endfor %}

{% endif %}
{% for url in urllist %}

    <img src="{{ url }}" width="100px">
{% endfor %}