I am trying to post a file in an Ajax request. It is working in Localhost but not after publish on server, it is always returning 404.
I don't know if it is a route problem.
I appreciate if someone can give me some idea.
My code is here:
View:
<form method="post" enctype="multipart/form-data">
<input type="file" id="files"
name="files" multiple />
<input type="button"
id="upload"
value="Upload Selected Files" />
Controller:
[HttpPost]
public IActionResult UploadFilesAjax()
{
long size = 0;
var files = Request.Form.Files;
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = hostingEnv.WebRootPath + $@"\{filename}";
size += file.Length;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
}
string message = $"{files.Count} file(s) / {size} bytes uploaded successfully!";
return Json(message);
}
Javascript:
@section Scripts {
<script type="text/javascript">
j(document).ready(function () {
j("#upload").click(function (evt) {
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
type: "POST",
url: "/Exemplos/UploadFilesAjax",
contentType: false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function (e) {
alert("There was error uploading files!");
}
});
});
});
</script>
As I have noticed in you POST method there is no route opened to the URL you defined. Please add route to the HttpPost attribute. It would looks like below,
[HttpPost("/Exemplos/UploadFilesAjax")]
public IActionResult UploadFilesAjax()
{
long size = 0;
var files = Request.Form.Files;
foreach (var file in files)
{
var filename = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
filename = hostingEnv.WebRootPath + $@"\{filename}";
size += file.Length;
using (FileStream fs = System.IO.File.Create(filename))
{
file.CopyTo(fs);
fs.Flush();
}
}
string message = $"{files.Count} file(s) / {size} bytes uploaded successfully!";
return Json(message);
}
I solve this problem by adding Route
attribute on controller
class like this:
[Route("/AreaName/[controller]/[action]")] // <-- this line
[ApiController]
public class GlobalController : ControllerBase
{
...
}
NOTE: if you haven't area
remove AreaName
part from rout path.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.