I am working with ASP.Net Core 2.1, and trying to upload a file while returning it's url, without refreshing the page.
I am trying to write the JavaScript in site.js as the _RenderPartial("scripts") renders all scripts at the end of the page and hence directly using script tag in the razor view is not working. Secondly, adding it to site.js gives me an opportunity to call the script across the site views.
My Controller action looks like :
[HttpPost]
[DisableRequestSizeLimit]
public async Task<IActionResult> Upload()
{
// Read & copy to stream the content of MultiPart-Form
// Return the URL of the uploaded file
return Content(FileName);
}
My view looks like :
<form id="FileUploadForm" action="~/Resources/Upload" method="post" enctype="multipart/form-data">
<input name="uploadfile" type="file" />
<button name="uploadbtn" type="submit" onclick="SubmitForm(this.parentElement, event)">Upload</button>
The site.js currently looks like :
function SubmitForm(form, caller) {
caller.preventDefault();
$.ajax(
{
type: form.method,
url: form.action,
data: form.serialize(),
success: function (data) { alert(data); },
error: function (data) { alert(data); }
})}
Presently, the code bypasses the entire script and the file is uploaded and new view displaying the file name is returned. I need help to create the javascript.
Unfortunately the jQuery
serialize()
method will not include input file elements. So the file user selected is not going to be included in the serialized value (which is basically a string).What you may do is, create a
FormData
object, append the file(s) to that. When making the ajax call, you need to specifyprocessData
andcontentType
property values tofalse
and here in the unobutrusive way to handle the form submit event where we will stop the regular behavior and do an ajax submit instead.
Assuming your server side method has a parameter of with name same as the one we used when we created the
FormData
object entry(file
). Here is a sample where it will upload the image to theuploads
directory insidewwwwroot
.The action method returns a JSON object with a status and url/message property and you can use that in the
success
/done
handler of the ajax call to whatever you want to do.