javascript - AJAX: Asynchronously posting a file to a server -


i want post file server asynchronously without posting form. have following code:

var fileinput = document.getelementbyid('fileinput'); var file = fileinput.files[0]; var formdata = new formdata(); formdata.append('file', file, file.name); var xhr = new xmlhttprequest(); xhr.open('post', 'http://servername/controllername/analysefile', true); xhr.setrequestheader('content-type', 'multipart/form-data'); xhr.send(formdata); 

however, when method executed on server, post body contains no files. following asp.net mvc4:

[httppost] public jsonresult analysefile() {   int filescount = request.files.count;   if(filescount == 0) { throw new exception('no files...'); }   // stuff } 

the files collection contains no files , can't figure out why. appreciated.

in view, can do:

<form> <input name="input1" id="input1"/> <input name="input2" id="input2"/> <input name="input3" id="input3"/> ... <input id="selectedfile" name="selectedfile" type="file"/> </form> 

and javascript:

function attlogic(_url, _data, _callback) {     $.ajax({         url: _url,         type: 'post',         xhr: function () {             var myxhr = $.ajaxsettings.xhr();             if (myxhr.upload) { }             return myxhr;         },         data: _data,         cache: !1,         success: _callback,         contenttype: !1,         processdata: !1     }); }  function formdatacustom(f) {     var __frm = jquery(f), data = new formdata(f);     $(':disabled[name]', __frm).each(function () {         data.append(this.name, $(this).val());     });     return data; }  function savelogic(){ var dt = formdatacustom(document.forms[0]); attlogic(yoururl, dt, function (r) {         //do here     }); } 

in controller:

public actionresult save(parameter1,parameter1,..., list<httppostedfilebase> selectedfile) {     //do here } 

Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -