【问题标题】:Issue with using Jquery File Upload on MVC 4. Multiple calls to Action?在 MVC 4 上使用 Jquery File Upload 时出现问题。多次调用操作?
【发布时间】:2014-03-11 11:54:00
【问题描述】:

我正在尝试在我的 MVC 4 应用程序上使用 jquery-file-upload 将多个图像上传到服务器。

我已经按照这个post实现了图片上传。

这是我的看法:

   @{
    ViewBag.Title = "Index";
}
<style>
    body
    {
        padding-top: 60px;
    }
</style>
<form action="/api/upload" enctype="multipart/form-data">
<div class="row fileupload-buttonbar">
    <div class="span7">
        <div class="well">
            <i class="icon-plus"></i><span>&nbsp;&nbsp;Add files...</span>
            <input type="file" id="fileupload" name="fileupload" accept="image/*" multiple="multiple">
            <button id="btnUploadAll" class="btn btn-success pull-right" type="button">
                Upload All</button>
            <div class="clearfix">
            </div>
            <div class="progress">
                <div class="bar" id="overallbar" style="width: 0%">
                </div>
            </div>
        </div>
    </div>
    <div class="span7">
        <div class="well hide" id="filelistholder">
        </div>
    </div>
    <div class="span7">
    </div>
</div>
</form>
@section PageScripts
{
    <script type="text/javascript">
        $(function () {
            $('#fileupload').fileupload({
                dataType: "json",
                url: "/api/upload",
                limitConcurrentUploads: 1,
                sequentialUploads: true,
                progressInterval: 100,
                maxChunkSize: 10000,
                add: function (e, data) {
                    $('#filelistholder').removeClass('hide');
                    data.context = $('<div />').text(data.files[0].name).appendTo('#filelistholder');
                    $('</div><div class="progress"><div class="bar" style="width:0%"></div></div>').appendTo(data.context);
                    $('#btnUploadAll').click(function () {
                        data.submit();
                    });
                },
                done: function (e, data) {
                    data.context.text(data.files[0].name + '... Completed');
                    $('</div><div class="progress"><div class="bar" style="width:100%"></div></div>').appendTo(data.context);
                },
                progressall: function (e, data) {
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    $('#overallbar').css('width', progress + '%');
                },
                progress: function (e, data) {
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    data.context.find('.bar').css('width', progress + '%');
                }
            });
        });
    </script>
   }

这里是 api 控制器:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Threading;
using System.Web.UI;
using System.IO;

namespace MvcTesting.Controllers.WebApi
{
    public class UploadController : ApiController
    {
        // Enable both Get and Post so that our jquery call can send data, and get a status
        [HttpGet]
        [HttpPost]
        public HttpResponseMessage Upload()
        {
            // Get a reference to the file that our jQuery sent.  Even with multiple files, they will all be their own request and be the 0 index
            HttpPostedFile file = HttpContext.Current.Request.Files[0];

            // do something with the file in this space 
             var uniqueFileName = GlobalVariables.UniqueFileNameGenerator(file.FileName);
        var path = GlobalVariables.UniqueFilePath(uniqueFileName, "~/Data/ObjectImages");
        file.SaveAs(path);

        var objImg = new ObjectImage
                         {
                             ObjectID = objectID,
                             ImageDescription = form.Get("ImageDescription"),
                             ImageFilePath = path,
                             ImageFileName = uniqueFileName,
                             ContentType = file.ContentType,
                             CreatedDate = DateTime.Now
                         };
        currentObject.ObjectImages.Add(objImg);
        _context.SaveChanges();
            // end of file doing

            // Now we need to wire up a response so that the calling script understands what happened
            HttpContext.Current.Response.ContentType = "text/plain";
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var result = new { name = file.FileName };

            HttpContext.Current.Response.Write(serializer.Serialize(result));
            HttpContext.Current.Response.StatusCode = 200;

            // For compatibility with IE's "done" event we need to return a result as well as setting the context.response
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
    }
}

这里的问题是该方法被多次调用(当我调试它时大约 12 次)而不是只有一次。结果,我在数据库中得到了 12 个条目而不是一个条目。

我希望该操作仅被我上传的文件数调用。或者这就是它可以跟踪用户界面最新的方式?

如果是这种情况,我该如何修复我的代码?

有没有办法检查请求的内容并将其与之前的内容进行比较,如果内容相同,如果内容不同则不执行任何操作然后保存?

谢谢

【问题讨论】:

    标签: jquery asp.net asp.net-mvc-4 jquery-file-upload


    【解决方案1】:

    问题是

    maxChunkSize: 10000,
    

    因为它将文件分成块,所以对同一个文件多次调用 api。如果您删除 maxChunkSize,它只会进行一次调用。但是,这也意味着您可以上传的文件大小受到限制,但对于图像,您应该没问题。

    【讨论】:

      【解决方案2】:

      试试这个:

           [AcceptVerbs(HttpVerbs.Post)]
          public HttpResponseMessage Upload()
          {
              // Get a reference to the file that our jQuery sent.  Even with multiple files, they will all be their own request and be the 0 index
              HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[0];
      
              //// do something with the file in this space 
              //// ....
              //// end of file doing
      
              System.Web.HttpContext.Current.Response.ContentType = "text/plain";
              System.Web.HttpContext.Current.Response.Write("{\"name\":\"" + file.FileName + "\",\"type\":\"" + file.ContentType + "\",\"size\":\"" + file.ContentLength + "\"}");
              return null;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-06
        • 1970-01-01
        • 2015-03-02
        • 1970-01-01
        • 2018-06-01
        相关资源
        最近更新 更多