Code
<formclass="cmxform form-horizontal tasi-form"Id="SubmitForm"Method="POST"action="ADD"Novalidate="novalidate"Enctype="Multipart/form-data"> @{ if(!ViewData.ModelState.IsValid) {<divclass="Alert Alert-danger alert-dismissable"> <button type="Button" class="Close"data-dismiss="Alert"aria-hidden="true">x</button>@string. Format ("operation failed: {0}", viewdata.modelstate["Error"]. errors[0]. ErrorMessage)</div> } } <divclass="Form-group">@Html. Labelfor (Item= = Item. Name,New{@class ="Control-label col-lg-2" }) <divclass="col-lg-10">@Html. Textboxfor (Item= = Item. Name,New{@class ="Form-control"}) </div> </div> <divclass="Form-group">@Html. Labelfor (Item= = Item. Linkurl,New{@class ="Control-label col-lg-2" }) <divclass="col-lg-10">@Html. Textboxfor (Item= = Item. Linkurl,New{@class ="Form-control" }) </div> </div> <divclass="Form-group">@Html. Labelfor (Item= = Item. ImgNew{@class ="Control-label col-lg-2" }) <divclass="col-lg-10"> <input type="file"Name="file" class="Form-control"/> </div> </div> <divclass="Form-group"> <divclass="col-lg-offset-2 col-lg-10"> <buttonclass="btn btn-success"Type="Submit"> Save </button> <buttonclass="btn Btn-default"Type="Button"onclick="Window.history.go ( -1);"> Back </button> </div> </div> </ Form>
Note: The form to add Enctype= "Multipart/form-data", indicating that there are files to submit.
To add httppostedfilebase file, file corresponds to the Name property of the upload control in HTML.
Background:
[HttpPost] Publicactionresult Add (Service.Dto.BannerInfoDto Dto, httppostedfilebase file) {stringFileName =""; if(File = =NULL) {Modelstate.addmodelerror ("Error","Please select a picture. Jpg/.png/.gif"); returnView (DTO); } if(File! =NULL) { stringFileext =path.getextension (file. FileName). ToLower (); if(!". Jpg/.png/.gif". Contains (Fileext)) {Modelstate.addmodelerror ("Error","The picture is not formatted correctly. Jpg/.png/.gif"); returnView (DTO); } fileName="~/uploadfile/bannerinfo/"+ DateTime.Now.ToString ("YYYYMMDDHHMMSS") +Fileext; stringSerpath =Server.MapPath (fileName); Try{file. SaveAs (Serpath); } Catch(Exception ex) {Modelstate.addmodelerror ("Error","Upload exception:"+Ex. Message); returnView (DTO); }} Domain.rl_bannerinfo Model= new Domain.rl_bannerinfo (); Model. Linkurl=DTOs. Linkurl; Model. Name=DTOs. Name; Model. IMG=FileName; BOOLresult =Bannerinfomanage.save (model); if(Result) {returnRedirecttoaction ("Manage"); } Else{modelstate.addmodelerror ("Error","Save failed"); returnView (DTO); } }
That's probably it.
MVC Uploading files