1. This article is using native JS to upload files, there are two versions, one without Ajax, one with Ajax.
1) Non-Ajax
<!DOCTYPE HTML><HTML><Head> <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/> <title></title> <MetaCharSet= "Utf-8" /></Head><Body><formID= "Upload-form"Action= "Template/uploadbusinessimage"Method= "POST"enctype= "Multipart/form-data"> <inputtype= "File"ID= "Upload"name= "Productimage"/> <BR/> <inputtype= "Submit"value= "Upload"/></form></Body></HTML>
2) AJAX
<!DOCTYPE HTML><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"/> <title></title> <MetaCharSet= "Utf-8"/> <Script> /*Native JS version*/ functionUpdatefile () {/*FormData is the form data class*/ varFD= NewFormData (); varAjax= NewXMLHttpRequest (); Fd.append ("Upload", 1); /*add files to the form*/Fd.append ("productimage", document.getElementById ("Upfile"). files[0]); Ajax.open ("Post", "Template/uploadbusinessimage", true); Ajax.onload= function() {console.log (ajax.responsetext); }; Ajax.send (FD); } </Script></Head><Body> <P><inputtype= "File"ID= "Upfile"></P> <P><inputtype= "button"ID= "Upjs"value= "Upload with native JS"onclick= "Updatefile ()"></P></Body></HTML>
2. Backstage
Publicactionresult uploadbusinessimage (httppostedfilebase productimage) {stringError =""; Try { //File UploadHttpPostedFileBase postfilebase =productimage; //file suffix stringExtension =path.getextension (postfilebase.filename); //file StreamStream Uploadstream =Postfilebase.inputstream; //write the file to the local e-drive using(varFileStream = System.IO.File.Create ("e:\\"+postfilebase.filename)) {Uploadstream.seek (0, Seekorigin.begin); Uploadstream.copyto (FileStream); } return This. Json (Error, Jsonrequestbehavior.allowget); } Catch(Exception e) {return This. Json (E.message, jsonrequestbehavior.allowget); } }
C # upload files with native JS