Flask-Uploads allows your application to flexibly and efficiently handle file uploading and serving the uploaded files. You can create different sets of uploads - one for document attachments, one for photos, etc. - and the application can be configured to save them all in different places and to generate different URLs for them.
環(huán)境及版本號:
- python 2.7.10
- Flask==0.11.1
- Flask-Uploads==0.2.1
上傳效果圖:
后臺邏輯代碼:
# main.py
# coding:utf-8
from flask import Flask, render_template, request
from flask_uploads import UploadSet, configure_uploads, ALL
app = Flask(__name__)
files = UploadSet('files', ALL)
app.config['UPLOADS_DEFAULT_DEST'] = 'uploads'
configure_uploads(app, files)
@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and 'media' in request.files:
filename = files.save(request.files['media'])
url = files.url(filename)
return render_template('upload.html')
if __name__ == '__main__':
app.run(debug=True)
前端模板代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload</title>
<link rel="stylesheet" >
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdn.bootcss.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
</head>
<body>
<form action="{{url_for('upload')}}" method="POST" enctype="multipart/form-data">
<input type="file" id="media" name="media">
<input type="submit">
</form>
<div class="progress" style="display: none;">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
0%
</div>
</div>
<script type="text/javascript">
$('form').on('submit', function (event) {
// 顯示進度條
$('.progress').css('display', 'block');
// 阻止元素發(fā)生默認的行為映之,此處用來阻止對表單的提交
event.preventDefault();
var formData = new FormData(this);
// jQuery Ajax 上傳文件炸枣,關鍵在于設置:processData 和 contentType
$.ajax({
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
var percent = Math.round(e.loaded * 100 / e.total);
$('.progress-bar').attr('aria-valuenow', percent).css('width', percent + '%').text(percent + '%');
}
});
return xhr;
},
type: 'POST',
url: '/upload',
cache: false,
data: formData,
// 告訴 jQuery 不要去處理發(fā)送的數(shù)據(jù)
processData: false,
// 告訴 jQuery 不要去設置 Content-Type 請求頭
// 因為這里是由 <form> 表單構造的 FormData 對象螟碎,且已經(jīng)聲明了屬性 enctype="multipart/form-data"结蟋,所以設置為 false
contentType: false
}).done(function (res) {
alert('上傳成功!');
}).fail(function (res) {
alert('上傳失敗!');
});
});
</script>
</body>
</html>