开发者

How do I upload an image file using MVC2

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.


  1. You need to ensure the <form> tag has a enctype="multipart/form-data" value in the object htmlAttribute paramter of Html.BeginForm()

  2. The name of the input file control should match the name of the parameter passed into the [HttpPost] Action method.

e.g.

<input type="file" name="uploadControl" />

should match 'name-wise' to:

public ActionResult AddPhoto(int id, FormCollection formValues, HttpPostedFile uploadControl, AlbumPhotos photo)

See http://www.277hz.co.uk/Blog/Show/7/image-uploading-in-asp-net-mvc for a good explanation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜