使用 ASP.NET MVC 进行多个文件上传jQuery 多文件上传插件

发布于 2024-08-16 19:15:32 字数 2664 浏览 4 评论 0原文

我正在使用 jQuery 多文件上传插件来上传多张图片。但表单仅发布 1 个顶部项目。 Fiddler(POST):

POST /Images/UploadImages HTTP/1.1
Host: localhost:4793
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost:4793/images
Cookie: .ASPXAUTH=EFAC4E03FA49056788028048AE1B099D3EB6D1D61AFB8E830C117297471D5689EC52EF40C7FE2CEF98FF6B7C8CAD3AB741A5E78F447AB361A2BDD501331A88C7B75120611CEA4FECA40D972BB9401472
Content-Type: multipart/form-data; boundary=---------------------------1509898581730
Content-Length: 290022

-----------------------------1509898581730
Content-Disposition: form-data; name="album"

1
-----------------------------1509898581730
Content-Disposition: form-data; name="file[]"; filename="Blue hills.jpg"
Content-Type: image/jpeg

...

这是我的代码:

<% using (Html.BeginForm("UploadImages", "Images", FormMethod.Post, new { enctype = "multipart/form-data"}))
       {%>

    <%= Html.DropDownList("album", (IEnumerable<SelectListItem>)ViewData["Albums"])%>
      <br />    
    <input type="file" name="file[]" id="file" class="multi" accept="jpg|png" />
      <br />
     <input type="submit" name="submit" value="Submit" />

    <% } %>

和控制器的代码:

public ActionResult UploadImages(FormCollection formValue)
    {           
        foreach (string file in Request.Files)
        {
            HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
            if (hpf.ContentLength == 0)
                continue;

            //do something with file
        }
        return RedirectToAction("Index");
    }

请告诉我如何解决问题。也许您可以建议其他方式让用户上传多张图像。蒂亚

PS。除了 sript 控件生成的 html 代码之外:

<input id="file" class="multi" type="file" accept="jpg|png" name="file[]" style="position: absolute; top: -3000px;"/>
<input id="file_F1" class="multi MultiFile" type="file" accept="jpg|png" name="file[]" style="position: absolute; top: -3000px;"/>
<input id="file_F2" class="multi MultiFile" type="file" accept="jpg|png" name="file[]" style="position: absolute; top: -3000px;"/>
<input id="file_F3" class="multi MultiFile" type="file" accept="jpg|png" name="file[]" style="position: absolute; top: -3000px;"/>
<input id="file_F4" class="multi MultiFile" type="file" accept="jpg|png" name="file[]"/>

I'm using jQuery Multiple File Upload Plugin to upload several pictures. But form posts only 1, top, item. Fiddler (POST):

POST /Images/UploadImages HTTP/1.1
Host: localhost:4793
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost:4793/images
Cookie: .ASPXAUTH=EFAC4E03FA49056788028048AE1B099D3EB6D1D61AFB8E830C117297471D5689EC52EF40C7FE2CEF98FF6B7C8CAD3AB741A5E78F447AB361A2BDD501331A88C7B75120611CEA4FECA40D972BB9401472
Content-Type: multipart/form-data; boundary=---------------------------1509898581730
Content-Length: 290022

-----------------------------1509898581730
Content-Disposition: form-data; name="album"

1
-----------------------------1509898581730
Content-Disposition: form-data; name="file[]"; filename="Blue hills.jpg"
Content-Type: image/jpeg

...

Here is my code:

<% using (Html.BeginForm("UploadImages", "Images", FormMethod.Post, new { enctype = "multipart/form-data"}))
       {%>

    <%= Html.DropDownList("album", (IEnumerable<SelectListItem>)ViewData["Albums"])%>
      <br />    
    <input type="file" name="file[]" id="file" class="multi" accept="jpg|png" />
      <br />
     <input type="submit" name="submit" value="Submit" />

    <% } %>

And controller's code:

public ActionResult UploadImages(FormCollection formValue)
    {           
        foreach (string file in Request.Files)
        {
            HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
            if (hpf.ContentLength == 0)
                continue;

            //do something with file
        }
        return RedirectToAction("Index");
    }

Please advise me how to solve the issue. Maybe you can advise other way to let user upload several images. TIA

PS. Besides html code of generated by the sript controls:

<input id="file" class="multi" type="file" accept="jpg|png" name="file[]" style="position: absolute; top: -3000px;"/>
<input id="file_F1" class="multi MultiFile" type="file" accept="jpg|png" name="file[]" style="position: absolute; top: -3000px;"/>
<input id="file_F2" class="multi MultiFile" type="file" accept="jpg|png" name="file[]" style="position: absolute; top: -3000px;"/>
<input id="file_F3" class="multi MultiFile" type="file" accept="jpg|png" name="file[]" style="position: absolute; top: -3000px;"/>
<input id="file_F4" class="multi MultiFile" type="file" accept="jpg|png" name="file[]"/>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

坚持沉默 2024-08-23 19:15:32

我找到了解决方案。答案是将 HttpPostedFileBase 更改为 IEnumerable(如果您要上传多个文件)。

我遇到了和你上面一样的问题。这解决了我的问题。这里还有一个很好的链接:Phil Haacks 的帖子

I found a solution. The answer was to change the HttpPostedFileBase to an IEnumerable (if you are uploading multiple files).

I had the same problem(s) as you above. This solved my problem. Here is a good link too:Phil Haacks's post

月下伊人醉 2024-08-23 19:15:32

问题是您正在尝试访问一个包含相同索引的数组,因为 POST 提交正在获取具有相同名称的文件数组。

而不是

foreach (string file in Request.Files)
{
        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;

使用

for (int i = 0; i < Request.Files.Count; i++)
{
        HttpPostedFileBase hpf = Request.Files[i];

The problem was you are trying to access an array which contains same index as the POST submit is obtaining an array of files with same name.

Instead of

foreach (string file in Request.Files)
{
        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;

use

for (int i = 0; i < Request.Files.Count; i++)
{
        HttpPostedFileBase hpf = Request.Files[i];
三五鸿雁 2024-08-23 19:15:32

您应该能够绑定到一个列表。

public ActionResult UploadImages(List<HttpPostedFileBase> file)
{ 
// magic
}

你的观点应该有

<input id="file" class="multi" type="file" accept="jpg|png" name="file" style="position: absolute; top: -3000px;"/>

You should be able to bind to a list.

public ActionResult UploadImages(List<HttpPostedFileBase> file)
{ 
// magic
}

and your view should have

<input id="file" class="multi" type="file" accept="jpg|png" name="file" style="position: absolute; top: -3000px;"/>
凝望流年 2024-08-23 19:15:32

在 HTML5 中,您可以使用单个文件上传字段上传多个文件:

<input type="file" id="files" name="files" multiple />

在这种情况下,您的操作方法可能类似于:

public ActionResult Index(List<HttpPostedFileBase> files) {

foreach (var file in files) {
  ...etc.

In HTML5, you can upload multiple files with a single file upload field:

<input type="file" id="files" name="files" multiple />

In that case, your action method can be something like:

public ActionResult Index(List<HttpPostedFileBase> files) {

foreach (var file in files) {
  ...etc.
戏剧牡丹亭 2024-08-23 19:15:32

我认为问题是生成的 HTML 中的名称 file[] 。显然,从插件方面来看,这个 si 工作得不好。

有时扭转正确的行为才是有效的。尝试从名称中删除“[]”并查看。

实际上,因为您没有按名称使用输入字段。您可以保留名称未设置,类似于插件的主页示例。

尝试一下。

I think the problem is the name file[] in the generated HTML. Clearly this si not working well from the plug-in side.

Sometimes reversing the right behavior is what works. Try to remove "[]" from the name and see.

Actually, since you are not using the input fields by name. You can leave the name unset similar to the homepage examples of the plug-in.

Give it a try.

长途伴 2024-08-23 19:15:32

我已经找到了应定义“namePattern”属性以便生成具有不同名称的输入。

例如:

<input type="file" accept="gif|jpg|jpeg|png" />


<script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $i = (1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
            $(':file').MultiFile({ namePattern: '$name_$i', maxlength: 20 });
        });  
</script>

不过,还是谢谢你的帮助。

I've found. The 'namePattern' property should be defined in order to generate inputs with different name.

For ex.:

<input type="file" accept="gif|jpg|jpeg|png" />


<script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $i = (1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
            $(':file').MultiFile({ namePattern: '$name_$i', maxlength: 20 });
        });  
</script>

Nevertheless, thank you for your help.

情话已封尘 2024-08-23 19:15:32

您可以查看此处来自 Phil Haack 的解决方案。

在视图上

<form action="" method="post" enctype="multipart/form-data">

  <label for="file1">Filename:</label>
  <input type="file" name="files" id="file1" />

  <label for="file2">Filename:</label>
  <input type="file" name="files" id="file2" />

  <input type="submit"  />
</form>

在控制器上

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
  foreach (var file in files) {
    if (file.ContentLength > 0) {
      var fileName = Path.GetFileName(file.FileName);
      var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
      file.SaveAs(path);
    }
  }
  return RedirectToAction("Index");
}

You can look here a solution from Phil Haack.

On the view

<form action="" method="post" enctype="multipart/form-data">

  <label for="file1">Filename:</label>
  <input type="file" name="files" id="file1" />

  <label for="file2">Filename:</label>
  <input type="file" name="files" id="file2" />

  <input type="submit"  />
</form>

On Controller

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
  foreach (var file in files) {
    if (file.ContentLength > 0) {
      var fileName = Path.GetFileName(file.FileName);
      var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
      file.SaveAs(path);
    }
  }
  return RedirectToAction("Index");
}
莳間冲淡了誓言ζ 2024-08-23 19:15:32

使用 jquery ajax 和 .net MVC 发布许多文件:

在视图中:

        <input type="file" name="files" multiple class="hidden"    id="inputFiles">
       <button id="upload" class="btn btn-sm btn-primary" type="button">Încarcă</button> 

在 js 中:

    var btnUpload = $("#upload");
var inputFiles = $('#inputFiles');

    btnUpload.click(function () {
    inputFiles.trigger('click');
});

inputFiles.on('change', function () {
    var formData = new FormData();

    for (var i = 0; i < inputFiles[0].files.length; i++)
        formData.append("files[" + i + "]", inputFiles[0].files[i])

    $.ajax({
        url: window.baseUrl + "Archivator/Upload",
        type: "POST",
        contentType: "application/json, charset=utf-8",
        dataType: "json",
        data: formData,
        processData: false,
        contentType: false,
    });
});

控制器中:

 [HttpPost]
    public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
    {

        return Content("Succesfully");
    }

Posting many file with jquery ajax and .net MVC:

In View:

        <input type="file" name="files" multiple class="hidden"    id="inputFiles">
       <button id="upload" class="btn btn-sm btn-primary" type="button">Încarcă</button> 

In js:

    var btnUpload = $("#upload");
var inputFiles = $('#inputFiles');

    btnUpload.click(function () {
    inputFiles.trigger('click');
});

inputFiles.on('change', function () {
    var formData = new FormData();

    for (var i = 0; i < inputFiles[0].files.length; i++)
        formData.append("files[" + i + "]", inputFiles[0].files[i])

    $.ajax({
        url: window.baseUrl + "Archivator/Upload",
        type: "POST",
        contentType: "application/json, charset=utf-8",
        dataType: "json",
        data: formData,
        processData: false,
        contentType: false,
    });
});

Controller:

 [HttpPost]
    public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
    {

        return Content("Succesfully");
    }
虐人心 2024-08-23 19:15:32

视图

<input type="file" id="updFiles" multiple name="updFiles" />  

控制器

if (Request.Files != null && Request.Files.Count > 0)  
{    
    for (int i = 0; i < Request.Files.Count; i++)  
    {  
        HttpPostedFileBase file = Request.Files[i];  
        if (file != null && file.ContentLength > 0)  
        {  
            var fileName = Path.GetFileName(file.FileName);  
            //store  
            var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);  
            file.SaveAs(path);  
        }  
    }  
}  

view

<input type="file" id="updFiles" multiple name="updFiles" />  

Controller

if (Request.Files != null && Request.Files.Count > 0)  
{    
    for (int i = 0; i < Request.Files.Count; i++)  
    {  
        HttpPostedFileBase file = Request.Files[i];  
        if (file != null && file.ContentLength > 0)  
        {  
            var fileName = Path.GetFileName(file.FileName);  
            //store  
            var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);  
            file.SaveAs(path);  
        }  
    }  
}  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文