TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Dima Alek
NA
43
1.9k
How to overwrite file in database with ajax
Jul 31 2020 3:29 AM
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) {
//$('#uploadStatus').html("ok");
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?
Reply
Answers (
4
)
Html 5 required validation with ajax without refreshing the page.
Post request failed from View to Controller.