2

i am having trouble uploading an image from the website to the server.

My ajax form is taking everything except the image file. I saw a similar question here ASP.Net MVC 5 image upload to folder

but i can't seem to get it to work

i have this

public HttpPostFileBase imageFile {get;set;}
public string imageText {get;set;}
public string imageTitle {get;set;}
public bool isActive {get;set;}
public DateTime dateAdded {get;set;}
public string urlRedirect {get;set;}

public ActionView Index()
{
   return View;
}

public void UploadImage (CarouselController carouselImage)
{
 // some code
}

my ajax begin form takes in all the fields with html razor.

@Html.TextBoxFor(model =>model.imageText , new {class = "form-control"} )
... similar for the other fields. 
for the image i have 

@html.TextBoxFor(model => model.imageFile), new { type="file"})

this makes it a working selection input box but it doesn't pass any information to the upload method.

see attached picture for what i mean. enter image description here

Community
  • 1
  • 1
173901
  • 699
  • 1
  • 7
  • 29
  • Is imageFile the actual file or the location of the image? – Gjohn Sep 30 '14 at 17:34
  • i'm not sure. It's the the equivelant to so would that be the image or the location? but either way i think it doesn't get passed because i have tried making HttpPostFileBase into string, Object, HttpPostFile, HttpPostFileBase, and in despiration i also tried a byte[] – 173901 Sep 30 '14 at 17:37

3 Answers3

2

You need to set the following attribute on your form:

enctype = "multipart/form-data"
Keith
  • 718
  • 8
  • 12
  • i'll give this a go. I wont be able to test it until a little later on. – 173901 Sep 30 '14 at 17:47
  • No unfortunately this still ddin't work, it continues populating with a null. – 173901 Sep 30 '14 at 18:19
  • And I also assume that your screen shot is out of date and your HttpPostFileBase is called "file" even though the screenshot calls it "imageFile"? – Keith Sep 30 '14 at 18:32
  • screenshot is the actual code. The other one is from memory. But i just checked, aside from the names. the code is pretty much spot on – 173901 Sep 30 '14 at 18:40
  • In that case I would double check you have the right names on these attributes. If you are trying to post something named "file", the server will only bind it to something named "file" – Keith Sep 30 '14 at 18:43
  • What is it you passed as HttpPostFileBase type, inherited class or means that HttpPostedFileBase? Please check your code – bashkan Sep 30 '14 at 18:56
1

It appears that you are trying to send a file along with a form that is posted with AJAX. If that is the case, then that's your problem: You can't send files this way. AJAX form posting only supports plain text values. For a work around, see my answer to this question.

Please let me know if you need any clarification.

Community
  • 1
  • 1
Tobias
  • 2,811
  • 2
  • 20
  • 31
0
public class ImageUpload
{
        public int ID { get; set; }       

        public string Title { get; set; }

        public string Description { get; set; }       

        [AllowHtml]       
        public string Contents { get; set; }

        public byte[] Image { get; set; }
}

public ActionResult Create()
{
     return View();
}

@using (Html.BeginForm("Create","Content", FormMethod.Post, new { enctype ="multipart/form-data" }))
{ 
   <input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
}

[Route("Create")]
[HttpPost]
public ActionResult Create(ImageUpload model)
{
    HttpPostedFileBase file = Request.Files["ImageData"];

    ContentRepository service = new ContentRepository();

    int i = service.UploadImageInDataBase(file, model);

    if (i == 1)
    {
         return RedirectToAction("Index");
    }

    return View(model);
}

private readonly ImageDBContext db = new ImageDBContext();

public int UploadImageInDataBase(HttpPostedFileBase file, ImageUplad imageupload)
{
        ImageUpload.Image = ConvertToBytes(file);
        var Content = new Content
        {
            Title = imageupload.Title,
            Description = imageupload.Description,
            Contents = imageupload.Contents,
            Image = imageupload.Image
        };

        db.Contents.Add(Content);

        int i = db.SaveChanges();

        if (i == 1)
        {
            return 1;
        }
        else
        {
            return 0;
        }
}

public byte[] ConvertToBytes(HttpPostedFileBase image)
{
    byte[] imageBytes = null;

    BinaryReader reader = new BinaryReader(image.InputStream);

    imageBytes = reader.ReadBytes((int)image.ContentLength);

    return imageBytes;
}

Step 6: Display an image form database on view. Here we display the content and image from the database.

public ActionResult Index()
{
    var content = db.Contents.Select(s => new
    {
        s.ID,
        s.Title,
        s.Image,
        s.Contents,    
        s.Description    
      });

      List<ImageUpload> imageModel = content.Select(item => new ImageUpload()    
      {    
            ID = item.ID,    
            Title = item.Title,    
            Image = item.Image,    
            Description = item.Description,    
            Contents = item.Contents    
        }).ToList();

       return View(imageModel);    
 }

<td>
     <img src="/Content/RetrieveImage/@item.ID" alt="" height=100 width=200 />
</td>

public ActionResult RetrieveImage(int id)
{
    byte[] cover = GetImageFromDataBase(id);

    if (cover != null)
    {
        return File(cover, "image/jpg");
    }
    else
    {
        return null;
    }
}

public byte[] GetImageFromDataBase(int Id)
{
    var q = from temp in db.Contents where temp.ID == Id select temp.Image;

    byte[] cover = q.First();

    return cover;
}

// Here is an example of how to upload an image and return its view. For more information, please refer to https://www.c-sharpcorner.com/UploadFile/b696c4/how-to-upload-and-display-image-in-mvc/

pushkin
  • 9,575
  • 15
  • 51
  • 95