javascript - 将文件列表发布到 ajax 帖子中的控制器
问题描述
我试图上传文件,但我无法通过列出我的控制器参数。我的情况是:
- 用户单击“选择文件”按钮并选择文件并按完成
- 然后我的一些函数获取文件列表并通过 POST merhod 传递给控制器以在本地保存,如下所示:
查看端:(获取文件列表)
function saveDocuments(documentList) {
if (documentList.length > 0)
{
var formList = new Array;
for (var i = 0; i < documentList.length; i++) {
var form = new FormData();
var file = documentList[i];
form.append('FormFile', file);
formList.push(form);
}
savePhysicalFile(formList);
}
}
查看端:(发布文件列表)
function savePhysicalFile(formData)
{
if (formData != null)
{
$.ajax({
url: "Installation/SavePhysicalPath",
type: 'POST',
dataType: "json",
contentType: "multipart/form-data",
data:formData,
processData: false,
contentType: false,
success: function (result) {
console.log("Success", result);
},
error: function (data) {
console.log(data);
}
});
}
}
在我的控制器端;参数“模型”始终为空。我不能在这里通过查看侧列表。我怎么知道?
控制器端
public JsonResult SavePhysicalPath([FromForm] List<FileModel> model)
{
var savingRootPath = @"C:\MyDocuments";
//I'm doing save locally
return Json(savingRootPath);
}
模型侧
public class FileModel
{
public string Files { get; set; }
public IFormFile FormFile { get; set; }
}
解决方案
从您的代码中,您可能会在这里注意两件事:
1.对于复杂类型的每个属性,模型绑定都会在源代码中查找名称模式prefix.property_name
。如果什么也没找到,它只寻找property_name
没有prefix
。model
因为你在后端收到的是一个列表,你需要给出类似的名称:[index].FormFile
或model[index].FormFile
。
2.你的模型有一个IFormFile
并且你的动作接收一个列表模型,如果你只传递你需要删除FromForm
属性的 IFormFile 并且确保没有。[ApiController]
这是一个已知的 github 问题,这已被移至Next sprint planning
里程碑。
这是一个完整的工作演示:
看法:
<input type="file" multiple onchange="saveDocuments(this.files)"/>
<div class="form-group">
<input type="button" value="Submit" id="submit" class="btn btn-primary" />
</div>
@section Scripts
{
<script>
function saveDocuments(documentList) {
if (documentList.length > 0) {
var form = new FormData();
for (var i = 0; i < documentList.length; i++) {
var file = documentList[i];
//change here
form.append('model['+i+'].FormFile', file);
}
savePhysicalFile(form);
}
}
function savePhysicalFile(formData) {
if (formData != null) {
$.ajax({
url: "/Installation/SavePhysicalPath",
type: 'POST',
dataType: "json",
contentType: "multipart/form-data",
data: formData,
processData: false,
contentType: false,
success: function (result) {
console.log("Success", result);
},
error: function (data) {
console.log(data);
}
});
}
}
</script>
}
控制器:
[HttpPost]
public JsonResult SavePhysicalPath(List<FileModel> model)
{
var savingRootPath = @"C:\MyDocuments";
//I'm doing save locally
return Json(savingRootPath);
}
结果:
推荐阅读
- go - 解码 json 值的更好方法
- r - R:如何在组 t 检验之间运行?
- amazon-web-services - 无法执行使用 Micronaut 和 Graal 构建的 AWS Lambda 函数:解码 JSON 流时出错
- python - 如何使用嵌套在另一个“for”循环中的“for”循环继续迭代 JSON 对象/列表?
- android - 改进 ML Kit 图像标记
- javascript - 如何告诉 ion-slides 要显示什么幻灯片 (slideTo)
- r - 如何计算一个文件夹中多个 csv 的行数?
- c# - 如何从 url 下载文件并保存到 FTP
- php - 如何发布 API 的新版本?
- javascript - 使用 Javascript 添加文本框