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;