我想知道是否有任何当前使用blueimp的jquery文件上传插件和flask框架的例子。如果有人要分享一些代码片段,我将不胜感激。
他们的布局似乎很好,我可以添加一个文件,并且预览得很好。问题是,当我尝试去上传它时,我得到这种错误: [12:47:58.690] POST [HTTP / 1.0 400 BAD REQUEST 7ms]
在服务器端,我甚至没有可以打印出来的有效文件对象,所以我认为这里的问题是代码的javascript部分(或者我也错了)。以下是我目前在模板方面使用的相关代码:
<form action="{{ url_for('upload') }}" method="post" enctype="multipart/form-data">
!-- The global progress bar -->
<div id="progress" class="progress progress-success progress-striped">
<div class="bar"></div>
</div>
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="icon-plus icon-white"></i>
<span>Add files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br><br>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
</form>
<script type="text/javascript" src="{{ url_for('static', filename='assets/js/jquery.ui.widget.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='assets/js/jquery.iframe-transport.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='assets/js/jquery.fileupload.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='assets/js/jquery.fileupload-process.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='assets/js/jquery.fileupload-image.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='assets/js/jquery.fileupload-audio.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='assets/js/jquery.fileupload-video.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static', filename='assets/js/jquery.fileupload-validate.js') }}"></script>
<script>
/*jslint unparam: true, regexp: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var uploadButton = $('<button/>')
.addClass('btn')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#fileupload').fileupload({
url: '/upload',
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append(file.error);
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
});
}).on('fileuploadfail', function (e, data) {
$.each(data.result.files, function (index, file) {
var error = $('<span/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
这是上传处理程序:
UPLOAD_FOLDER = 'static/tmp/'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
def _handleUpload(files):
if not files:
return None
filenames = []
saved_files_urls = []
for key, file in files.iteritems():
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
print os.path.join(UPLOAD_FOLDER, filename)
file.save(os.path.join(UPLOAD_FOLDER, filename))
saved_files_urls.append(url_for('uploaded_file', filename=filename))
filenames.append("%s" % (file.filename))
print saved_files_urls[0]
return filenames
@app.route('/upload', methods=['POST'])
def upload():
try:
message = request.values['message']
files = request.files
print files, message
uploaded_files = _handleUpload(files)
return jsonify({'files': uploaded_files})
except:
raise
return jsonify({'status': 'error'})
答案 0 :(得分:0)
将上传方法更改为:
@app.route('/upload', methods=['POST'])
def upload():
try:
files = request.files
print files
uploaded_files = _handleUpload(files)
return jsonify({'files': uploaded_files})
except:
raise
return jsonify({'status': 'error'})