本文介绍了在Asp.Net Core中使用Ajax上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好日子,
我正在尝试使用ajax从客户端上传文件到服务器端(asp.net核心)控制器但是我有一个null值。
I'm trying to upload file using ajax from client side to server side (asp.net core) controller but I'm having a null value.
这是我的html和javascript代码:
Here's my html and javascript codes:
<input type="file" id="myfile" class="required" />
<button type="button" class="btn btn-info" onclick="uploadcsvfile()">
<script>
function uploadcsvfile() {
var myfile= document.getElementById("myfile");
var formData = new FormData();
if (myfile.files.length > 0) {
for (var i = 0; i < myfile.files.length; i++) {
formData.append('file-' + i, myfile.files[i]);
}
}
$.ajax({
url: "/MyController/UploadFile/",
type: "POST",
dataType: "json",
data: formData,
contentType: false,
processData: false,
success: function(data){
},
error: function (data) {
}
})
}
</script>
这是我的控制器使用IFormFile
Here's my controller that uses IFormFile
public async Task<JsonResult> UploadFile(IFormFile formData)
{
// do something here
}
提前谢谢!
推荐答案
很好地解释了:
<form id="form" name="form" action="/uploader" enctype="multipart/form-data" method="post">
<div class="buttons">
<div class="upload-button">
<div class="label">Click me!</div>
<input id="files" name="files" type="file" size="1" multiple onchange="uploadFiles('files');" />
</div>
</div>
</form>
JavaScript
JavaScript
function uploadFiles(inputId) {
var input = document.getElementById(inputId);
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
$.ajax(
{
url: "/uploader",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
alert("Files Uploaded!");
}
}
);
}
服务器端代码:
Server Side Code:
[HttpPost]
public async Task<IActionResult> Index(IList<IFormFile> files)
{
foreach (IFormFile source in files)
{
string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
using (FileStream output = System.IO.File.Create(this.GetPathAndFilename(filename)))
await source.CopyToAsync(output);
}
return this.View();
}
private string EnsureCorrectFilename(string filename)
{
if (filename.Contains("\\"))
filename = filename.Substring(filename.LastIndexOf("\\") + 1);
return filename;
}
private string GetPathAndFilename(string filename)
{
return this.hostingEnvironment.WebRootPath + "\\uploads\\" + filename;
}
这篇关于在Asp.Net Core中使用Ajax上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!