Upload images or files asynchronously in. net MVC,. netmvc
Today, I used MVC to upload images asynchronously. After half a day, I wrote it down to facilitate searching.
Asynchronous image submission requires a MyAjaxForm. cs address http://pan.baidu.com/s/1i3lA693 password txgp
Front-end code
@ Using (Ajax. beginForm ("AddMessages", "MenuInfo", new AjaxOptions {HttpMethod = "post", OnSuccess = "Successd"}, new {@ id = "from1 ", enctype = "multipart/form-data"}) // it is best to add enctype = "multipart/form-data "}{
<Input id = "IconUrl" name = "IconUrl">
<Input type = "file" id = "files" name = "files" value = "click to select an image"/>
}
JS Code
Function fileUp () {$ ("# files "). change (function () {if ($ (this ). val () {// when the image is uploaded, $ ("# from1") is submitted asynchronously "). ajaxSubmit ({type: "Post",/* set the form to be submitted using the post method */dataType: "text",/* set the return value type to text */url: '/MenuInfo/uploadimag',/* set the page on which post is submitted */success: function (data) {$ ("# IconUrl "). val (data); // assign the returned address to that input $ ("# files "). val (""); // remove the value }})}})}
Background code
Public ActionResult UploadImage () {if (Request. Files ["files"]! = Null) // determine whether the uploaded image can be received {var imgurl = Request. files ["files"]; // obtain the uploaded image string fileEx = Path. getExtension (imgurl. fileName); if (fileEx = ". jpg "| fileEx = ". jpeg ") {// This type stores string imagePath ="/Upload/Images/"+ DateTime. now. year + "/" + DateTime. now. month + "/" + DateTime. now. day + "/"; if (! Directory. exists (imagePath) {// determines whether this folder Exists and no Directory is created. createDirectory (Server. mapPath (imagePath);} // write the Save path to store string fileName = imagePath + Guid. newGuid (). toString () + imgurl. fileName; imgurl. saveAs (Server. mapPath (fileName); return Content (fileName);} return Content ("only images in. jpg).jpeg format supported");} else {return Content ("failed to save ");}}