简体   繁体   中英

Upload Image before submit form in mvc3 asp.net

i am using asp.net MVC3

I want to upload the image before form is submit.

below is my code

 <div>
   @using (Html.BeginForm("SaveData", "Home", FormMethod.Post, new { @enctype =      "multipart/form-data" }))
   {
     <div> Image: 
           <input type="file" name="uploadFile" onchange="upload(this);" /></div>
     <div> Name: 
           @Html.TextBoxFor(model => model.Name)</div>
     <div> Address:  
           @Html.TextBoxFor(model => model.Address)</div>
     <div> Phone: 
           @Html.TextBoxFor(model => model.Phone)</div>

     <input type="submit" name="save" id="savedata" title="save" 
        value="save"  />
}         
</div>

<script type="text/javascript">
   function UploadFile(image) {
        //call controller action UploadFile
         $.ajax({
            type: "Post",
            url: "Home/UploadFile",
            data: image,       //This is wrong
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });
   }
</script>

Now on Controller side

 public ActionResult UploadFile(HttpPostedFileBase uploadFile)
 {
     //save image
 }

can any one can suggest how can i upload the image before posting my form to save data.

$.ajax() is not capable of that. There are jQuery plugins available though, that do this for you. Here's one . This thread also discusses loads of options to do this. Do note that file upload through AJAX is a relatively new feature and not all browsers support it .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM