Step-1) Create database table like
CREATE TABLE [dbo].[LuckyDrawHistory](
[LuckyDrawHistoryId] [bigint] IDENTITY(1,1) NOT NULL,
[LuckyDrawDate] [datetime] NULL,
[Description] [nvarchar](max) NULL,
[ImageName] [nvarchar](max) NULL,
[ImageBytes] [image] NULL,
CONSTRAINT [PK_LuckyDrawHistory] PRIMARY KEY CLUSTERED
([LuckyDrawHistoryId] ASC ))
Step-2) In MVC view
//To show already saved image or default image
@{
string imgDataURL = "../../DashboardAssets/imgs/avatar.png";
if (Model.ImageFile != null)
{
string extension = string.Empty;
extension = Path.GetExtension(Model.ImageExtension);
byte[] byteData = Model.ImageBytes;
//Convert byte arry to base64string
string imreBase64Data = Convert.ToBase64String(byteData);
imgDataURL = string.Format("data:image/" + extension + ";base64,{0}", imreBase64Data);
}
}
<img src="@imgDataURL" id="previewimage9" class="rounded-circle" style="height:150px;width:150px; margin-bottom: 15px; cursor: pointer;" />
<input id="image2" name="file2" type="file" class="fileUpload" onchange="readURL(this);" style="width: 90px;" />
<script>
function readURL(input) {
var ext = $('#image2').val().split('.').pop().toLowerCase();
if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
bootbox.alert("Invalid Image format, Image format must be JPG, JPEG, PNG or GIF.");
return;
}
var picsize = (input.files[0].size);
if (picsize > 1000000) {
bootbox.alert("Maximum file size limit is 1MB.");
return;
}
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#previewimage9')
.attr('src', e.target.result)
.width(150)
.height(150);
};
reader.readAsDataURL(input.files[0]);
$.blockUI();
var historyId = $("#hdHistoryId").val();
var formData = new FormData();
var totalFiles = document.getElementById("image2").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("image2").files[i];
formData.append("myImage", file);
}
$.ajax({
type: "POST",
url: '/Winner/UploadImage?historyId=' + historyId,
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
$.unblockUI();
bootbox.alert("Image has been uploaded successfully.");
}
});
}
}
</script>
Step-3) In MVC Controller
public ActionResult UploadImage(string historyId)
{
EFModel _db = new EFModel ();
byte[] fileData = null;
string fileName = string.Empty;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileName = Request.Files[0].FileName;
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
var ad = _db.LuckyDrawHistories.Find(historyId);
ad.ImageBytes = data;
ad.ImageName = fileName;
_db.Configuration.ValidateOnSaveEnabled = false;
_db.SaveChanges();
var msg = "Success||";
msg = msg + "/Winner/Index/";
return Content(msg);
}