【问题标题】:Kendo UI Core - Upload - How to call MVC ControllerKendo UI Core - 上传 - 如何调用 MVC 控制器
【发布时间】:2014-08-14 08:55:22
【问题描述】:

我正在使用 Kendo UI Core(免费版)并想将文件上传到 Web 服务器(通过 MVC 控制器)。我知道付费 Kendo UI 版本的方式,但我想使用免费版本。

如下图

用于剑道 UI 上传的 HTML

<div class="demo-section k-header">
<input name="files" id="files" type="file" />
</div>

Java 脚本

$("#files").kendoUpload({
    async: {
        saveUrl: "save",
        removeUrl: "remove",
        autoUpload: true
    }

});

它添加了一个按钮,如下所示:

现在,一旦我选择了文件,我想通过 MVC 控制器将其上传到服务器。

我应该如何从这里调用 MVC 控制器?

干杯

【问题讨论】:

标签: jquery html asp.net-mvc-4 kendo-ui kendo-upload


【解决方案1】:

对于 Kendo UI Core(根据您调用控制器操作上传文件的问题):-

$("#files").kendoUpload({
async: {
    saveUrl: "controllername/actionname",    //OR// '@Url.Action("actionname", "controllername")'   
    removeUrl: "controllername/actionname",  //OR// '@Url.Action("actionname", "controllername")'
    autoUpload: true
  }
});

例如,如果 Controller 和 Action 名称是 UploadSave 用于保存和删除上传的文件 Controller 和 Action 名称是 UploadRemove 然后:-

 $("#files").kendoUpload({
 async: {
    saveUrl: "Upload/Save",     //OR// '@Url.Action("Save", "Upload")'
    removeUrl: "Upload/Remove", //OR// '@Url.Action("Remove", "Upload")'
    autoUpload: true
  }
});

Kendo 文件上传小演示(用于 kendo ui web):-

查看:-

<form method="post" action='@Url.Action("Submit")' style="width:45%">
    <div class="demo-section">
        @(Html.Kendo().Upload()
            .Name("files")
        )
        <p>
            <input type="submit" value="Submit" class="k-button" />
        </p>
    </div>
</form>

控制器:-

 public ActionResult Submit(IEnumerable<HttpPostedFileBase> files)
    {
        if (files != null)
        {
            TempData["UploadedFiles"] = GetFileInfo(files);
        }

        return RedirectToAction("Index");
    }

 private IEnumerable<string> GetFileInfo(IEnumerable<HttpPostedFileBase> files)
    {
        return
            from a in files
            where a != null
            select string.Format("{0} ({1} bytes)", Path.GetFileName(a.FileName), a.ContentLength);
    }

完整的文档在这里:- http://demos.telerik.com/aspnet-mvc/upload/index


对于异步文件上传:-

查看:-

<div style="width:45%">
    <div class="demo-section">
        @(Html.Kendo().Upload()
            .Name("files")
            .Async(a => a
                .Save("Save", "Upload")
                .Remove("Remove", "Upload")
                .AutoUpload(true)
            )
        )
    </div>
</div>

控制器:-

 public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
        {
            // The Name of the Upload component is "files"
            if (files != null)
            {
                foreach (var file in files)
                {
                    // Some browsers send file names with full path.
                    // We are only interested in the file name.
                    var fileName = Path.GetFileName(file.FileName);
                    var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);

                    // The files are not actually saved in this demo
                    // file.SaveAs(physicalPath);
                }
            }

            // Return an empty string to signify success
            return Content("");
        }

        public ActionResult Remove(string[] fileNames)
        {
            // The parameter of the Remove action must be called "fileNames"

            if (fileNames != null)
            {
                foreach (var fullName in fileNames)
                {
                    var fileName = Path.GetFileName(fullName);
                    var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);

                    // TODO: Verify user permissions

                    if (System.IO.File.Exists(physicalPath))
                    {
                        // The files are not actually removed in this demo
                        // System.IO.File.Delete(physicalPath);
                    }
                }
            }

            // Return an empty string to signify success
            return Content("");
        }

【讨论】:

  • 谢谢例外。它看起来相当不错。我今天会试一试并更新答案。欢呼
  • 很遗憾没有
  • @user2739418...我的回答与您给出的相同...在我的回答中上传的是控制器名称,在您的回答中是其主页...'@Url.Action("Save", "Home")'... 与 /Home/Save... 相同
  • @user2739418...由'@Url.Action("Save", "Home")'生成的url...将是'/Home/Save',正如我在回答中提到的那样。 .但不同之处在于,在您的情况下,控制器在家,而在我的回答中,它上传了,因为我采用了假设的控制器和操作名称,因为您的问题中没有给出...
【解决方案2】:

我对此有点“Duh”,并意识到如果您不指定 .SaveField 属性,则控件的名称必须与控制器上的参数相同。

带有 SaveField 的 .cshtml 页面上的代码:

Html.Kendo().Upload()
     .Multiple(false)
     .Name("controlName")
     .Async(a => a
         .Save("SavePhoto", "Upload")
         .AutoUpload(true)
         .SaveField("fileParameter")
     );

样品控制器:

public ActionResult SavePhoto(IFormFile fileParameter)

如果您省略了 SaveLoad:

Html.Kendo().Upload()
     .Multiple(false)
     .Name("uploadFiles")
     .Async(a => a
         .Save("SavePhoto", "Upload")
         .AutoUpload(true)             
     );

它不会起作用。 在这种情况下,控件的名称必须与控制器中的参数匹配:

public ActionResult SavePhoto(IFormFile uploadFiles)

【讨论】:

    【解决方案3】:

    设置包装器以节省时间

    @(Html.Kendo().Upload().HtmlAttributes(new { Style = "width:300px;" })
        .Name("upImport")
        .Messages(e => e.DropFilesHere("Drop files here").Select("Select file"))
        .Multiple(false)
    
        .Async(a => a
            .Save("UploadFile", "File")
            .Remove("RemoveFile", "File")
            .AutoUpload(true)
            .SaveField("files")
        )
    
        .Events(events => events
            .Error("onError")               
            .Success("onSuccess")
        )
    )
    

    在您的服务器 mvc 应用程序上,您可能有 FileService.UploadFile() 或类似的东西。

    public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> files)
    {
        ServerFileModel model = new ServerFileModel();
        try
        {
            // The Name of the Upload component is "files" 
            if (files == null || files.Count() == 0)
                throw new ArgumentException("No files defined");
            HttpPostedFileBase file = files.ToArray()[0];
    
            if (file.ContentLength > 10485760)
                throw new ArgumentException("File cannot exceed 10MB");
    
            file.InputStream.Position = 0;
            Byte[] destination = new Byte[file.ContentLength];
            file.InputStream.Read(destination, 0, file.ContentLength);
    
            //IGNORE THIS
            ServerFileFormatEnum type = TempFileStorageController.GetFileFormatForExtension(Path.GetExtension(file.FileName));
            ServerFileDescriptor serverFile = TempFileStorageController.AddFile(destination, type);
            //IGNORE ABOVE
    
            model.FileIdentifier = serverFile.FileIdentifier;
            model.FileName = file.FileName;
            model.FileSize = file.ContentLength;
        }
        catch (Exception e)
        {
            model.UploadError = e.Message;
        }
        return Json(model, JsonRequestBehavior.AllowGet);
    }
    

    【讨论】:

      【解决方案4】:

      终于成功了:

      它的工作方式如下。

         $("#files").kendoUpload({
              async: {
                  saveUrl: '@Url.Action("Save", "Home")',
                  removeUrl: '@Url.Action("Remove", "Home")',
                  autoUpload: false
              }
      
          });
      

      这就是我调用 Kendo UI 窗口控件的方式,它与上传的方式相同

      Save是Action(Function),而Home是Controller类名

      【讨论】:

        猜你喜欢
        • 2013-06-09
        • 1970-01-01
        • 1970-01-01
        • 2015-02-07
        • 2013-10-24
        • 2015-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多