我正在尝试使用JQuery和C#MVC上传任意数量的文件。当我创建表单数据并发布它时,Request.Files对象为null。
返回的消息是“请确保您已上传所有必要的文件。”
如何将动态创建的输入文件传递给c#side? p>
这是HTML
<div style="text-align:center; display:block; width:100%; margin-bottom:20px" id="regPDFUpload"></div>
然后我使用以下代码附加文件上传元素:
//create file uploaders
var i = response.pdfPageCount;
for (j = 0; j < i; j++) {
var _file = '<label style="float:left; width:100px; padding-top:15px;" for="filePDFUpload' + j + '">Page ' + (j + 1) + '</label><input type="file" style="width:70%; display: block; float:left; margin-bottom:7px;" id="filePDFUpload' + j + '" name="filePDFUpload' + j + '" />';
_file += '<div style="clear:left"></div>';
$('#regPDFUpload').append(_file);
}
以下是JQuery 将文件添加到formData
var i = $('#regdoc-page-count').val();
var formData = new FormData();
//add files to form data
for (j = 0; j < i; j++) {
formData.append('filePDFUpload' + j, 'filePDFUpload' + j);
}
formData.append("customerGUID", $('#Customer-Guid').val());
formData.append("tempAccountNumber", $('#Temp-Account-Number').val());
$.ajax({
cache: false,
url: 'uploadRegDoc',
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: regUpoadSignedRegistrationSucess,
complete: resetWait,
error: regFailure
});
这是C#代码
[ValidateInput(false)]
[HttpPost]
public ActionResult UploadRegDoc(FormCollection form)
{
if (Request.Files.Count > 0)
{
//create customers folder in content/customer-doc
string filepath = "";
filepath = Server.MapPath("~/content/customer-docs/" + form["customerGUID"] + "/signed/");
if (!System.IO.Directory.Exists(filepath))
{
System.IO.Directory.CreateDirectory(filepath);
}
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
fname = Path.Combine(filepath, fname);
file.SaveAs(fname);
}
//redirect to
return Json(new
{
success = true,
message = "redirect",
resultId = (int)UserRegistrationType.AdminApproval,
});
}
catch (Exception ex)
{
//registration complete.
return Json(new
{
success = false,
message = "An error occured uploading your files. " + ex.Message,
});
}
}
else
{
//registration complete.
return Json(new
{
success = true,
message = "Please make sure you have uploaded all necessary documents.",
});
}
}
答案 0 :(得分:0)
非常感谢adeneo对上述答案的评论。将创建一个正式的答案,使其得到回答。
将JQuery代码附加到formData对象。它需要附加文件上传元素中的文件。
更新了JQuery代码:
>>> dcsv = np.atleast_2d(dcsv)