trying save file db. using formdata via javascript append file , adding post object via ajax. reason nothing gets sent.
what doing wrong?
html
<input type="file" style="display: none;" class="btn btn-primary uploadfile">
script:
$(".saveimage") .on("click", function() { var files = $(".uploadfile"); var data = new formdata(); data = $.overwatch.worker.uploadfilehandler.adduploadfiles(files, data); $.overwatch.worker.postuserdata("/administration/adduserimage", data, function () { alert("done"); }); });
functions above like:
adduploadfiles: function (files, data) { $.each(files, function (i, v) { var file = $(this).data("files"); data.append("file", file); }); return data; }
postuserdata:
postuserdata: function(url, data, callback) { $.loadingoverlay("show"); $.ajax({ url: url, type: 'post', data: data, cache: false, processdata: false, contenttype: false, datatype: "html", success: function(data) { if (callback) { callback(data); $.loadingoverlay("hide"); } }, error: function(event, jqxhr, settings, thrownerror) { //$.helpers.errorhandler($("#filedialogerrors"), event.responsetext); var h; $.loadingoverlay("hide"); } }); },
backend:
public actionresult adduserimage() { if (request.files.count != 0) { //save } return null; }
edit:
var files = $(".uploadfile");
returns:
your var file = $(this).data("files");
line of code returning undefined
(unless have other javascript adding data
value, cannot add files data
in case not returning file).
change loop to
$.each(files, function (i, v) { (i = 0; < v.files.length; i++) { var file = v.files[i]; data.append("file", file); } });
however, can simplify using var data = new formdata($('form').get(0));
serialize form controls including file inputs formdata
(refer how append whole set of model formdata , obtain in mvc more information).
i recommend change method signature to
public actionresult adduserimage(ienumerable<httppostedfilebase> files)
and let defaultmodelbinder
magic.
Comments
Post a Comment