HTML:
<div class="img-upload-panel">
<div>
<img
class="view-image" src="" />
<input type="hidden" id="hdnImageName" value="" />
<input type="file"
id="selectedImageFile" class="d-none" />
</div>
<button class="btn btn-primary btn-sm"
id="btnImgChange"><i class="fa
fa-camera"></i> Change Image</button>
</div>
JS:
$('#btnImgChange').on('click', function () {
$('#selectedImageFile').val("");
$("#selectedImageFile").click();
});
$('#selectedImageFile').on('change', function () {
var data = new FormData();
var files =
$("#selectedImageFile").get(0).files;
if (files.length > 0) {
data.append("image", files[0]);
}
//validation
var size =
$('#selectedImageFile')[0].files[0].size;
var extension =
$('#selectedImageFile').val().replace(/^.*\./, '');
if (size > 1000000) {
// Show Error
Message
return;
}
var fileExtension = ['jpeg',
'jpg', 'png', 'gif', 'bmp'];
if ($.inArray(extension,
fileExtension) == -1) {
//Show Error Message
return;
}
$.ajax({
url:'Home/UploadImage',
type: "POST",
processData:
false,
contentType:
false,
data: data,
success: function
(response) {
if
(response != "") {
$('.view-image').attr('src', '~/Images/' + response);
$('#hdnImageName').val(response);
}
else
{
//Show Error Message
}
},
error: function
(er) {
//Show Error Message
}
});
});
C#:
[HttpPost]
public string UploadFile()
{
try
{
if
(Request.Files.Count != 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
string fileName = DateTime.Now.ToString("yyMMddhhmmss") +
"_" + file.FileName;
var path = Path.Combine(Server.MapPath("~/images/"),
fileName);
file.SaveAs(path);
return fileName;
}
return "";
}
return
"";
}
catch (Exception ex)
{
return
"";
}
}
No comments:
Post a Comment