我已经使用剑道上传在MVC核心中使用Ajax Post上传文件。我可以调用 API 网址,但数据为空。我是否正确传递了数据?这是我的代码。
<form id="uploadForm" action='@Url.Action("UploadFile", new { RmclientAccid = "1" , AsAtDate = "testdate"})' method="post">
@(Html.Kendo().Upload()
.HtmlAttributes(new { aria_label = "files" })
.Name("fileUpload")
)
<p style="padding-top: 1em; text-align: right">
<button type="submit" class="k-button k-primary">Submit</button>
</p>
</form>
$(function () {
$("#uploadForm").submit(function (e) {
e.preventDefault();
var upload = $("#fileUpload").data("kendoUpload"),
files = upload.getFiles(),
myFile = files[0];
console.log(files);
$.ajax({
type: 'POST',
url: '/RmReportTasks/UploadFile/',
dataType: 'json',
processData: false,
contentType: false,
data: {
fileUpload: files[0].rawFile,
RmclientAccid: "1",
AsAtDate: "testdate"
},
success: function (data) {
console.log("succcess")
},
error: function (err) {
console.log("failure");
}
});
});
});
这是我的控制器。
[HttpPost]
public async Task<JsonResult> UploadFile(IEnumerable<IFormFile> fileUpload , string RmclientAccid, string AsAtDate)
{
var result = await _fileUploadManager.UploadDocument(fileUpload, RmclientAccid, AsAtDate);
return Json(result);
}
不能直接使用ajax
将文件发送到服务器。
$(function () {
$("#uploadForm").submit(function (e) {
e.preventDefault();
var formData = new FormData();
var totalFiles = document.getElementById("uploadForm").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("uploadForm").files[i];
formData.append("uploadForm", file);
}
$.ajax({
type: 'POST',
url: '/RmReportTasks/UploadFile/',
dataType: 'json',
processData: false,
contentType: false,
data: formData,
success: function (data) {
console.log("succcess")
},
error: function (err) {
console.log("failure");
}
});
});
});
在服务器端,您可以像这样接收文件。
[HttpPost]
public void UploadFile()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
// Write logic to handle file here.
}
}
您可以在没有表单标签元素的情况下执行此操作。
您的CSHTML
代码应为:
@(Html.Kendo().Upload()
.Name("uploadFiles")
.HtmlAttributes(new { aria_label = "files" })
)
您的 AJAX 调用应该是:
function OnBrowseSaveClick(e)
{
var uploadControl = $("#uploadFiles").data("kendoUpload"); //get a reference of the Upload
var files = uploadControl.getFiles(); //Get the uploaded files
var formData = new FormData();
for (var i = 0; i < files.length; i++) { //loop through the files
var file = files[i].rawFile;
formData.append("uploadFiles", file); //append the property "rawFile" that holds the actual file in the FormData
}
$.ajax({
url: '/Home/SaveFile',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(result) {
alert('Success');
},
error: function(result) {
swal("Error :" + result.responseText);
}
});
}
控制器操作应为:
public ActionResult SaveFile(IEnumerable<IFormFile> uploadFiles)
{
// The Name of the Upload component is "uploadFiles" in the partial view.
if (uploadFiles != null)
{
foreach (var file in uploadFiles)
{
var fileContent = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
// Some browsers send file names with full path.
// The sample is interested only in the file name.
var fileName = Path.GetFileName(fileContent.FileName.ToString().Trim('"'));
var physicalPath = Path.Combine(_webHostEnvironment.WebRootPath, "documents", fileName);
using (var fileStream = new FileStream(physicalPath, FileMode.Create))
{
file.CopyTo(fileStream);
}
}
}
// Return an empty string to signify success.
return Content("");
}