I have written a small script using jquery to upload a file to a server. The file is uploaded successfully and the done: event is called with no problems, but I am having issues to process the answer. This is my script:
<input id="fileupload" type="file" name="carPicture" accept="image/*" multiple>
<div id="progress">
<div class="bar" style="width: 0%;"></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/vendor/jquery.ui.widget.js")" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/jquery.iframe-transport.js")" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/jquery.fileupload.js")" type="text/javascript"></script>
<script>
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = "uploadCarPicture";
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
fail: function (e, data) {
alert("File exists");
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
I am having two problems:
the variable data seems to be empty since the loop below doesn't run even once.
$.each(data.result.files, function (index, file) { $('<p/>').text(file.name).appendTo('#files'); });The answer is a JSON document with the following format: {"e":0} where "e" is an error code. "e" could return many different values and I would like to be able to find out the real response and not always assume 0.
Any idea?
$.each, you should be using$(data).each.{"e":0}, then the object obviously does not have aresultproperty, so you cannot iterate overdata.result.files.