Posting form data and file using jquery ajax to asp.net core rc2 -
this question has answer here:
i trying post form has input text field , file upload control using jquery ajax. however, keep getting 404 not found error. below, have included relevant part of razor code brevity:
here sample of razor code:
<form id="uploadform" asp-action="fileupload" asp-controller="content" method="post" enctype="multipart/form-data"> <input asp-for="title" class="form-control" required /> <input asp-for="uploadformfile"> <button type="button" id="uploadbutton" class="btn btn-primary" >upload</button> </form>
javascript:
$(document).ready(function () { $("#uploadbutton").click(function (e) { var data = new formdata($("uploadform").serialize()); var uploadedfile = $("#uploadformfile").get(0).files[0]; data.append(uploadedfile.name, uploadedfile); $.ajax({ url: '@url.action("fileupload", "content")', type: "post", data: data, contenttype: false, datatype: false, processdata: false, success: function (result) { alert(result); } }); }); });
controller action:
[httppost] public async task<iactionresult> fileupload() { cancellationtoken cancellationtoken = default(cancellationtoken); long size = 0; var files = request.form.files; foreach (var file in files) { var filename = contentdispositionheadervalue .parse(file.contentdisposition) .filename .trim('"'); filename = $@"\{filename}"; size += file.length; using (var filestream = new filestream(filename, filemode.create)) { ... } } string message = $"{files.count} file(s)/{ size} bytes uploaded successfully!"; return json(message); }
i tried using answer here, still 404
the time did not 404 when changed formdata below , did not append uploaded file:
var data = new formdata($("uploadform")[0]);
however, in case, controller action not receive data , request.form null.
so, possible submit form data along file using jquery ajax in asp.net mvc core rc2?
thanks.
use this
var formdata = new formdata(); var uploadedfile = document.getelementbyid("uploadformfile").files[0]; formdata.append(uploadedfile.name, uploadedfile); var xhr = new xmlhttprequest(); xhr.open("post", '@url.action("fileupload", "content")', true); xhr.send(formdata);
hope you
Comments
Post a Comment