简体   繁体   中英

Sending data inside the type file to the controller in ASP.NET MVC

I want to sending a photo for posting blog!

I have defined two properties in my model. One for the name of the photo to be stored in the database and And another one to get the file and save to the server (in Resources Folder).

this is my model code :

[DataType(DataType.Upload)]
public HttpPostedFileBase File { get; set; }

public string BlogImage { get; set; }

this is my HTML code :

<div class="form-group col-sm-8">
                    <label for="BlogImage">Blog Image</label>
                    <input type="file" class="form-control" id="BlogImage">
                </div>

I want to send the file to the server with AJAX.

 var myAdminBlog = {
    BlogImage: $("#BlogImage").val(),
    File: $("#BlogImage").val()
};

$.ajax({
    url: 'AddPostBlog',
    data: JSON.stringify(myAdminBlog),
    type: "POST",
    contentType: "application/json;charset=utf-8",
    dataType: "json",
    success: function (data) {
        alert(data);
    },
    error: function (errormessage) {
        alert(errormessage);
    }
});

This is my Ajax Code.

Finally, you can see the controller code.

 public JsonResult AddPostBlog(csAdminBlog myAdminBlog)
    { 
       int UploadMessage = UploadImage(myAdminBlog);
       return Json("Post Sended", JsonRequestBehavior.AllowGet);

    }

My problem is exactly that I do not know how to get the file from javascript.

I tried to use the $("#BlogImage").val() method, but failed.

Note: All codes work well and all information is sent to the controller , Only the item that is not sent is the File option

If it is not necessary to be in jQuery then you can use document.getElementById(BlogImage).files[0]

Create Class like this

Public Class UploadFile
{
[DataType(DataType.Upload)]
public HttpPostedFileBase File { get; set; }

public string BlogImage { get; set; }

}

Then in javascript

 var UploadFile= new Object();
 UploadFile.BlogImage = $("#BlogImage").val();
 UploadFile.File = document.getElementById(BlogImage).files[0];

$.ajax({
   url: 'AddPostBlog',
   data: JSON.stringify({uploadFile:UploadFile}),
   type: "POST",
   contentType: "application/json;charset=utf-8",
   dataType: "json",
   success: function (data) {
      alert(data);
   },
   error: function (errormessage) {
      alert(errormessage);
   }

});

And In Controller Method

 public JsonResult AddPostBlog(UploadFile uploadFile)
 { 
  //Your Code

}

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