c# - File uploads to asp.net web api using pure javascript via ajax -
i trying file uploads through ajax
web api. server side codes prove working cause have managed post files using debugging fiddler , works fine. failing write successful javascript code able upload.
below html code:
function sendimage() { var data = new formdata(); var file = document.getelementbyid('upload').files[0]; data.append("image",file); if (window.xmlhttprequest) {// code ie7+, firefox, chrome, opera, safari xmlhttp_br=new xmlhttprequest(); } else {// code ie6, ie5 xmlhttp_br=new activexobject("microsoft.xmlhttp"); } xmlhttp_br.onreadystatechange = function () { if (xmlhttp_br.readystate == 4 ) { var data = xmlhttp_br.responsetext; alert(xmlhttp_br.status+" "+data); var file = json.parse(data); } } xmlhttp_br.open("post","http://localhost:59103/"+"api/upload/testupload",true); xmlhttp_br.setrequestheader("content-type","multipart/form-data"); xmlhttp_br.setrequestheader("filename", file.name); xmlhttp_br.send(data); }
<input name="uploadedimage" id="upload" type="file" accept="image/*"> <button onclick="sendimage()"> upload image </button> <img id ="image">
my c#
server side code follows
public async task<ihttpactionresult> postfile() { httprequestmessage request = this.request; if (!request.content.ismimemultipartcontent()) { throw new httpresponseexception(httpstatuscode.unsupportedmediatype); } var provider = new multipartmemorystreamprovider(); await request.content.readasmultipartasync(provider); stream img = null; string filename =""; foreach (var file in provider.contents) { filename = file.headers.contentdisposition.filename.trim('\"'); img = await file.readasstreamasync(); //do whatever want filename , binaray data. } bool status = uploadfiletos3(filename, img, "edu-media"); if (status) { return ok(); } else { return statuscode(httpstatuscode.expectationfailed); } }
note saving files aws s3 buckets
, don't want jquery
, pure javascript.
Comments
Post a Comment