[英]How to upload multiple files into C# and loop through them in MVC
I'm having a problem with uploading multiple files to C# and loop through them. 我在将多个文件上传到C#并循环遍历它们时遇到问题。 I found a question with a similar problem but nobody answered it.
我发现了一个类似问题的问题,但没有人回答。
I upload multiple files through an html input. 我通过html输入上传了多个文件。 The file count passes through to my controller with the correct amount relative to the amount of files I selected.
文件计数以正确的数量(相对于我选择的文件数量)传递到我的控制器。 However when I try to loop through each of my files it loops through the first file relative to the file count.
但是,当我尝试遍历每个文件时,它会遍历第一个相对于文件计数的文件。 For example if I upload 3 files it loops through the first file 3 times or if I upload 5 files it loops through the first file 5 times.
例如,如果我上传3个文件,它将循环浏览第一个文件3次,或者如果我上传5个文件,则循环浏览第一个文件5次。 It should not do this.
它不应该这样做。 I want it to loop through each file individually.
我希望它逐个循环遍历每个文件。 Please help!!!
请帮忙!!! here is my code:
这是我的代码:
Razor View(I'm using a bootstrap library for fileinputs called bootstrap-filestyle): Razor View(我正在使用引导程序库来进行名为bootstrap-filestyle的文件输入):
@using (Html.BeginForm("Initial", "DataCapture", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<h4>Select files</h4>
<input type="file" multiple="multiple" id="fileToUpload" name="file">
</div>
<div>
<input type="submit" value="Capture" class="btn btn-default" />
</div>
}
Controller: 控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Initial(ClaimModel claimModel)
{
if (ModelState.IsValid)
{
//OtherCode
handleFile(Request.Files, c.ClaimID);
return RedirectToAction("Index", "ClaimFiles", new { id = c.ClaimID });
}
//OtherCode
}
private void handleFile(HttpFileCollectionBase Files, int ClaimID)
{
foreach (string fileName in Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//OtherCode
}
//OtherCode
}
I put break points on handleFile(Request.Files, c.ClaimID);
我在
handleFile(Request.Files, c.ClaimID);
上放置了断点handleFile(Request.Files, c.ClaimID);
and inside foreach (string fileName in Files){...}
. 在
foreach (string fileName in Files){...}
内部foreach (string fileName in Files){...}
。 As I said it correctly passes through the file count if I upload 3, 4, 5 or any amount of files however it only loops through the first file that amount of times and return
s the first file multiple times as well. 正如我所说,如果我上传3、4、5或任意数量的文件,它将正确地通过文件计数,但是它只会循环访问该数量的第一个文件,并多次
return
第一个文件。 I need it to loop through and return each file individually. 我需要它遍历并分别返回每个文件。 How do I do this correctly?
如何正确执行此操作?
Use Request from server , here is one example: 使用来自服务器的请求 ,这是一个示例:
for (int i = 0; i < Request.Files.Count; i++)
{
var fileDoc = Request.Files[i];
}
Or you can try something like this: 或者,您可以尝试执行以下操作:
HttpPostedFileBase hpf = null;
foreach (string file in Request.Files)
{
hpf = Request.Files[file] as HttpPostedFileBase;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.