I'm trying to replace some file in my DB using ajax call. I can not understand how to pass data(file) from my tag into controller, maybe somebody can give me an advise...
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);
- }
- }
my JS:
- 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?