ASP.NET MVC 4 , Ajax Image Upload
Sunday, August 25, 2013 Category : ASP.NET MVC 1
<tr>
<th>
@Html.LabelFor(m => m.NewsBody)
</th>
<td>
@Html.TextAreaFor(m => m.NewsBody, new { @class = "my-textBox" })
@Html.ValidationMessageFor(m => m.NewsBody)
</td>
</tr>
<script type="text/javascript">
// Call this function on upload button click after user has selected the file
function UploadFile() {
var file = document.getElementById('etlfileToUpload').files[0];
if(file == null) {return;}
var fileName = file.name;
var fd = new FormData();
fd.append("fileData", file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
xhr.open("POST", "/AP/FileUpload", true);
xhr.send(fd);
}
function UploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
$("#uploading").text(percentComplete + "% ");
}
}
function UploadComplete(evt) {
if (evt.target.status == 200){
//alert(evt.target.responseText);
$("#uploading").text("Upload Success");
$(".path").text(evt.target.responseText);
document.getElementById('etlfileToUpload').parentNode.innerHTML = document.getElementById('etlfileToUpload').parentNode.innerHTML;
}
else {
$("#uploading").text("Error Uploading File");
//alert("Error Uploading File");
}
}
function UploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function UploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
[HttpPost]
public JsonResult FileUpload(HttpPostedFileBase fileData)
{
string path = "";
if (fileData != null)
{
string pic = System.IO.Path.GetFileName(fileData.FileName);
path = System.IO.Path.Combine(Server.MapPath("~/news.resource"), pic);
// file is uploaded
fileData.SaveAs(path);
path = pic;
// save the image path path to the database or you can send image directly to database
// in-case if you want to store byte[] ie. for DB
/*using (MemoryStream ms = new MemoryStream())
{
fileData.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}*/
}
// after successfully uploading redirect the user
return Json(path);
//return RedirectToAction("actionname", "controller name");
}