Reputation: 113
I am trying to upload a file, send it to the controller with ajax and save it in the database. Without Ajax, it is working perfectly, but when I submit the code with ajax in the controller I get a 0 result and cannot save the files into the DB.
Here is my code: View:
<form method="post" id="uploadForm" enctype="multipart/form-data" asp-action="UploadFile">
<div class="k-content">
@(Html.Kendo().Upload()
.Name("files")
.Multiple(true)
.Messages(m=>m.Select("Select"))
.Validation(validation => validation
.AllowedExtensions(new string [] { ".doc", ".docx", ".pdf", ".txt"})
.MaxFileSize(5242880)
)
.HtmlAttributes(new { aria_label = "files"})
)
<p style="padding-top: 1em; text-align: right">
<button type="submit" id="uploadfile" class="btn btn-outline-primary rounded-pill">Upload</button>
</p>
</div>
</form>
The ajax call:
$("#uploadfile").click(function (e) {
e.preventDefault();
var fileUpload = $("#addfile").data("kendoUpload"),
files = fileUpload.getFiles();
var filedata = new FormData();
for (var i = 0; i < files.length; i++) {
filedata.append(files[i].name, files[i]);
}
$.ajax({
type: "POST",
url: '@Url.Action("UploadFile")',
contentType: false,
processData: false,
data: filedata,
success: function (message) {
alert(message);
},
error: function (xhr, status, error) {
alert(error);
},
});
});
And the controller, which works fine without ajax, but when data is submitted with Ajax, I get 0 result for the filedata
[HttpPost]
public async Task<IActionResult> UploadFile(IEnumerable<IFormFile> filedata)
{
foreach (var f in filedata)
{
if (f != null)
{
if (f.Length > 0)
{
var fileName = Path.GetFileName(f.FileName);
var fileExtension = Path.GetExtension(fileName);
var objfiles = new FileUpload
{
FileName = fileName,
FileType = fileExtension,
FileSize = f.Length,
CretedOn = DateTime.UtcNow,
};
using (var target = new MemoryStream())
{
f.CopyTo(target);
objfiles.FileData = target.ToArray();
}
_context.FileUploads.Add(objfiles);
}
}
else
{
return Ok(false);
}
}
await _context.SaveChangesAsync();
return Ok(true);
}
Upvotes: 0
Views: 1360
Reputation: 1
the simple compelete solution for this is following
js code
var fileupload = $("#FileUpload").get(0);
var files = fileupload.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append('files', files[i]);
}
controller use IFormFile instead of IEnumerable
public IActionResult UploadFile(IFormFile files)
{
**for storing in your project folder**
string filePath = "";
if (files != null) {
string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "uploads");
filePath = Path.Combine(uploadsFolder, files.FileName);
using(var fileStream = new FileStream(filePath, FileMode.Create))
{
files.CopyTo(fileStream);
}
}
Upvotes: 0
Reputation: 8459
You should use rawFile
, as it holds the actual file data. And the key name should be corresponding to the receive parameter.
for (var i = 0; i < files.length; i++) {
filedata.append("filedata", files[i].rawFile);
}
Upvotes: 1