Есть приложение, в которое я хотел бы загрузить изображение. Я использую байтовый массив для этого.
Изображение требуется, но когда я помещаю эту аннотацию в переменную и пытаюсь создать изображение, оно выдает мне сообщение об ошибке, когда там должно быть изображение. Также возвращается, что модель недействительна.
Когда я удаляю Required, он работает, но его также можно установить как null, чего я не хочу.
По теме переполнения стека не так много.
Вот моя модель
[Key]
public int InvoiceId { get; set; }
[Required(ErrorMessage = "Company is required")]
public string Company { get; set; }
[Required(ErrorMessage = "Description is required")]
public string Description { get; set; }
[Required(ErrorMessage = "Amount is required")]
public decimal Amount { get; set; }
[Required(ErrorMessage = "Picture of Invoice Required")]
public byte[] PictureOfInvoice { get; set; }
И мой контроллер:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Parish Admin, Priest, Administrator")]
public ActionResult Create([Bind(Include = "InvoiceId,Company,Description,Amount,PictureOfInvoice,DateReceived,ChurchId")] Invoice invoice,HttpPostedFileBase File)
{
if (ModelState.IsValid)
{
if (File != null && File.ContentLength > 0)
{
invoice.PictureOfInvoice = new byte[File.ContentLength];
File.InputStream.Read(invoice.PictureOfInvoice, 0, File.ContentLength);
}
else
{
TempData["Error"] = "Upload an Image";
}
db.Invoices.Add(invoice);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", invoice.ChurchId);
return View(invoice);
}
My View на всякий случай, если что-то есть:
<h2>Add New Invoice</h2>
@if (TempData["Error"] != null)
{
<div style="color:red">@TempData["Error"]</div>
}
@using (Html.BeginForm("Create", "Invoices", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Company, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Company, new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
@Html.ValidationMessageFor(model => model.Company, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Amount,new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
@Html.ValidationMessageFor(model => model.Amount, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DateReceived, "DateRecieved", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.DateReceived, new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
@Html.ValidationMessageFor(model => model.DateReceived, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PictureOfInvoice, "Picture of Invoice", htmlAttributes: new { @class = "control-label col-md-2"})
<div class="col-md-10">
<input type="file" name="File" id="File" style="width: 50%;" />
@Html.ValidationMessageFor(model => model.PictureOfInvoice, "", new { @class = "text-danger" })
<output id="list"></output>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ChurchId, "Church Name", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ChurchId", null, htmlAttributes: new { @class = "form-control", style = "width:20em;" })
@Html.ValidationMessageFor(model => model.ChurchId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
<u>
@Html.ActionLink("Back to List", "Index")
</u>
</div>
<script src="~/Scripts/jquery.datetimepicker.js"></script>
<script>
$('#DateReceived').datetimepicker({
format: 'd/m/Y',
weeks: true,
disableWeekDays: [0, 1, 3, 4, 5, 6],
timepicker: false,
inline: false
});
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('File').addEventListener('change', handleFileSelect, false);
</script>