I'm trying to overwrite an old file with new one via ajax call in .Net MVC.
until now i can retreve data from DB but have no idea how to make overwrite.
Can somebody help me here?
What I have tried:
Here is my Controller:
[HttpPost]
public JsonResult UpdateFile(int id, HttpPostedFileBase postedFile)
{
byte[] bytes;
using (BinaryReader br = new BinaryReader(postedFile.InputStream))
{
bytes = br.ReadBytes(postedFile.ContentLength);
}
using (FileDBEntities db = new FileDBEntities())
{
tblFile fupt = db.tblFiles.Where(x => x.id == id).FirstOrDefault();
fupt.Name = Path.GetFileName(postedFile.FileName);
fupt.ContentType = postedFile.ContentType;
fupt.Data = bytes;
db.SaveChanges();
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
and my javascript:
function loadFileData() {
$.ajax({
type: "GET",
url: "/File/FileIndex",
dataType: "JSON",
success: function (data) {
$.each(data, function (i, val) {
var trow = $('<tr/>');
var trowb = $('<tr/>').data("id", val.id);
trow.append('<td colspan="2">' + val.Name + " " + '</td>');
trowb.append('<td><input style="width:250px;" type="file" id="choose" /></td><td><input type="button" value="upload" id="upload" /></td>');
tab.append(trow);
tab.append(trowb);
});
$("#showFiles").html(tab);
},
error: function () {
alert("Failed! Please try again.");
}
});
var tab = $('<table style="width:300px" border=1 class=MyTable></table>');
tab.on("click", "#upload", function (e) {
var tr = $(this).closest("tr");
var id = tr.data("id");
var input = $('#choose').file;
$.ajax({
type: "POST",
url: "/File/UpdateFile",
dataType: "JSON",
data: {
id: id,
pospostedFile: input
},
success: function (data) {
$('#uploadStatus').html("ok");
loadFileData();
},
error: function () {
alert("Failed! Please try again.");
}
});
});
}
Debbuger says me that I'm sending "null" as "postedFile". How can I take this value from input and feed it to my Controller?