简体   繁体   中英

How to upload “one” image to a database with Entity Framework and MVC 4

I am trying to write an image upload service for my PostController in the Create action, however I am getting a compile error saying:

'System.Array' does not contain a definition for 'InputStream'/ContentLength and no extension method 'InputStream'/ContentLength accepting a first argument of type 'System.Array'

On these lines:

    using (var binaryReader = new BinaryReader(uploadImage.InputStream))
    {
        imageData = binaryReader.ReadBytes(uploadImage.ContentLength);
    }

I only want to upload one file and no more. I am also unsure if this is correct: singlepart/form-data in the Html.Begin form.

I did try HttpPostedFileBase uploadImage instead of HttpPostedFileBase[] uploadImage however I got an error of instance is not set to an object on this line:

using (var binaryReader = new BinaryReader(uploadImage.InputStream))

It should be noted that post.Picture is (varbinary(max)) in my Post table.

View:

@using (Html.BeginForm("Create", "Post", FormMethod.Post, new { enctype = "singlepart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>

            <div class="col-xs-6 col-md-4">
                @Html.LabelFor(model => model.Picture)

            <div class="editor-field">
                <input type="file" name="uploadImages" class="input-files" />
                @Html.ValidationMessageFor(model => model.Picture)
            </div>
        </div>

Controller:

    [Authorize]
    public ActionResult Create()
    {
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize]
    public ActionResult Create([Bind(Include = "BlogUserEmail,CategoryId,Title,ShortDescription,Description")]Post post, HttpPostedFileBase[] uploadImage, string selectedTags)
    {
        if (uploadImage != null)
        {
            return RedirectToAction("Create");
        }

        byte[] imageData = null;

        using (var binaryReader = new BinaryReader(uploadImage.InputStream)) // not set to an instance of an object
        {
            imageData = binaryReader.ReadBytes(uploadImage.ContentLength);
        }
        var Image = new Post
        {
             Picture = imageData
        };

        post.Picture = Image.Picture;

You are correctly worried about singlepart/form-data , since it is not valid encoding method. Html forms support following encodings:

  • application/x-www-form-urlencoded (the default)
  • multipart/form-data (allows posting of files)
  • text/plain

So you have to use multipart/form-data to post files.

Then you can modify Create method to only accept single HttpPostedFileBase "

public ActionResult Create([Bind(Include = "BlogUserEmail,CategoryId,Title,ShortDescription,Description")]Post post, HttpPostedFileBase uploadImage, string selectedTags)

You get this error because you have an Array of objects and you try to use ContentLength / InputStream which is a property of HttpPostedFileBase

Instead of uploadImage.InputStream you can take first element if you try tu upload just 1 image uploadImage[0].InputStream or uploadImage.First().InputStream . Or instead you can remove [] .

Also you have to change enctype from "singlepart/form-data" to "multipart/form-data"

The input have the name uploadImages and the parameter of the action uploadImage , change the input according

<input type="file" name="uploadImage" class="input-files" />

I recommend you to use a model that will encapsulate all form elements.

public class PostCreateModel : Post
{
    public HttpPostedFileBase uploadImage { get; set; }
    public string selectTags { get; set; }
}

And Action will look like this. Don't forget to change @model in View.

public ActionResult Create(PostCreateModel post)
{
    if (post.uploadImage != null)
    {
        return RedirectToAction("Create");
    }

    byte[] imageData = null;

    using (var binaryReader = new BinaryReader(post.uploadImage.InputStream)) // not set to an instance of an object
    {
        imageData = binaryReader.ReadBytes(post.uploadImage.ContentLength);
    }
    var Image = new Post
    {
         Picture = imageData
    };

    post.Picture = Image.Picture;

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