使用ASP上传图片.NET MVC4剃须刀

本文关键字:NET MVC4 剃须刀 ASP 使用 | 更新日期: 2023-09-27 17:57:33

我正在使用剑道移动构建一个移动应用程序,用户可以在其中点击并上传照片。当他们第一次进入页面时,它会显示他们的当前照片,我希望能够点击并打开他们设备上的文件资源管理器,并能够显示他们照片的预览,以取代旧照片。然后当点击完成时,它会把它发送到我的MVC控制器,然后我可以把它发送给我想要的地方。我不知道如何将我的文件发送到控制器。

HTML

<div id="NewAccountUploadContainer">
<img id="NewAccountUpload" src="~/Images/btnCamera.png" data-bind="click: uploadPhoto" />
@using (Html.BeginForm("SendNewPhoto", "MobilePlatform", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <input id="ImageUploadBtn" style="display: none" type="file" accept="image/*" />
    <input type="submit" value="OK" style="display: none" />
}
<div id="ImgUploadTxt" data-bind="click: uploadPhoto">
    Upload a<br />
    different photo.
</div>

#ImageUploadBtn将由jquery中的#NewAccountUpload或#ImgUploadTxt点击触发,这是有效的,但当我触发提交时,我无法让它显示文件或发送到我的控制器。

C#控制器

[HttpPost]
    public ActionResult SendNewPhoto(HttpPostedFileBase file)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0)
        {
            // extract only the fielname
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");
    }

此时该文件始终为null。

使用ASP上传图片.NET MVC4剃须刀

我使用的是用于mvc4的Kendo和移动实现,我使用的代码如下:

视图:@(Html.Kendo().Upload().Name("文件"))

控制器

public ActionResult Submit(IEnumerable<HttpPostedFileBase> files)
        {
            if (files != null)
            {
                TempData["UploadedFiles"] = GetFileInfo(files);
            }
            return RedirectToAction("Result");
        }
        public ActionResult Result()
        {
            return View();
        }
        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);
        }