views:

109

answers:

1

Im trying to us a controller in MVC2 to upload a file but i get an object reference not set to an instance of an object error

    [HttpPost]
    public ActionResult AddPhoto(int id, FormCollection formValues, HttpPostedFile image, AlbumPhotos photo )
    {            
        AlbumPhoto photos = new AlbumPhoto();
        UserPhotoAlbum album = AlbumRepo.GetAlbum(id);
        photo.AlbumId = id;
        photos.AlbumId = photo.AlbumId;
        photo.PostedDate = DateTime.Now;
        photos.PostedDate = photo.PostedDate;
        album.LastUpdate = photo.PostedDate;

        if (image.FileName != null)
        {
            photo.PhotoMimeType = image.ContentType;
            photos.PhotoMimeType = image.ContentType;
            photo.PhotoData = new byte[image.ContentLength];
            photos.PhotoData = photo.PhotoData;
            image.InputStream.Read(photo.PhotoData, 0, image.ContentLength);
            photo.PhotoUrl = "../../Content/UserPhotos/" + image.FileName;
            photos.PhotoUrl = photo.PhotoUrl;
            image.SaveAs(Server.MapPath("~/Content/UserPhotos/" + image.FileName));
        }

        AlbumRepo.AddPhotoToAlbum(photos);
        AlbumRepo.Save();

        return RedirectToAction("Album", new { id = photo.AlbumId });
    }

Please tell me if i'm doing something wrong.

A: 

Here's a quick way to upload a file:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
 if (file == null)
  throw new ArgumentException();

 var fileName = Path.GetFileName(file.FileName);
 file.SaveAs(@"C:\Temp\" + fileName);

 return RedirectToAction("Index");
}

And your corresponding form would look like this:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
 <form action="/MyController/Upload" method="post" enctype="multipart/form-data">

   <label>Filename: <input type="file" name="file" /></label>
   <input type="submit" value="Submit" />

 </form>
</asp:Content>

Note the use of enctype="multipart/form-data" if you want to submit multiple files.

Alex
i have that in place
stay
the data is sent to a repository that contains the date for the image and a corresponding object
stay
it seems as if the posted file image is not being read by the form itself
stay