问题在于,将文件类型对象数组传递给MVC模型操作时,$。post调用存在问题
我正在做的是使用jquery.filedrop库多次删除。然后,在删除所有项目并按下按钮后,所有这些文件都将被发送到名为“上载”的操作中。
HTML代码
<h2>Upload</h2>
<legend>Upload a file</legend>
<div class="editor-field">
<input type="file" id="file" name="file" />
</div>
<h2>Drag & Drop file upload </h2>
<div id="dropArea"></div>
<h4>Uploaded files : </h4>
<ul class="list-group" id="uploadList"></ul>
<input id="submsion" type="submit" />
JavaScript代码:
$(function () {
$('#dropArea').filedrop({
allowedfileextensions: ['.doc', '.docx', '.pdf', '.jpg', '.jpeg', '.png', '.PNG', '.gif', '.txt'],
maxfiles: 3,
maxfilesize: 5, // in MB
dragOver: function () {
$('#dropArea').addClass('active-drop');
},
dragLeave: function () {
$('#dropArea').removeClass('active-drop');
},
drop: function () {
$('#dropArea').removeClass('active-drop');
},
afterAll: function (e) {
$('#dropArea').html('file(s) uploaded successfully');
},
uploadFinished: function (i, file, response, time) {
$('#uploadList').append('<li class="list-group-item">' + file.name + '</li>')
addToFilePile(file)
}
})
})
var arrayOfFiles = [];
var singularObject;
$('#file').on('change', function () {
singularObject = $('#file').val();
});
function addToFilePile(file) {
arrayOfFiles.push(file);
}
$('#submsion').click(function () {
var finalPile = [];
if (arrayOfFiles != null) {
finalPile = arrayOfFiles;
if (singularObject != null) {
finalPile.push(singularObject);
}
}
else if (singularObject != null) {
finalPile = singularObject;
}
else {
//both are empty - do something about it
}
console.log(finalPile);
$.post('@Url.Action("Home", "Upload")', { files: finalPile }, function (data) {
console.log("POST done");
});
});
C#操作代码:
[HttpPost]
[ActionName("Upload")]
public ActionResult Upload(IEnumerable <HttpPostedFile> files)
{
if (files != null)
{
foreach (var item in files)
{
if (item != null)
{
string pathname = Path.Combine(@"D:\Projects\SavingFile\UploadedFiles", Path.GetFileName(item.FileName));
item.SaveAs(pathname);
}
}
}
return View();
}
当前,使用拖放操作时,Edge中出现0: Invalid calling object
错误,而Chrome中出现Uncaught TypeError: Illegal invocation
,这不是很有帮助。并且从<input>
中选择文件时,出现以下错误消息:HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
(XHR)POST - http://localhost:51348/Upload/Home
答案 0 :(得分:0)
有几个问题。
1)jQuery.ajaxSettings.traditional = true
需要将数组传递到IEnumarable
2)'@Url.Action("Home", "Upload")'
-> '@Url.Action("Upload")'
这可能会修复某些问题。
但是,呼叫成功,但是IEnumarable
始终为空,并且解决方法如下:How to upload files using ajax to asp.net mvc controller action