在asp mvc中使用json上传图像

时间:2014-01-08 05:09:53

标签: asp.net-mvc json asp.net-mvc-4

我有一个将所选文件上传到asp mvc4文件夹的功能。视图页面中的代码是

<form id="form1" method="post" enctype="multipart/form-data" action="EmployeeDetails/Upload">
<input type='file' id="imgInp" accept="image/jpeg"/>
    <p>
        <input type="submit" value="Upload" class="btn"/>
    </p>
</form>

控制器代码是

[HttpPost]
        public ActionResult Upload(HttpPostedFileBase imgInp)
        {
            if (imgInp != null && imgInp.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(imgInp.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/images/Profile"), fileName);
                imgInp.SaveAs(path);
            }
            return view("Index");
        }

而不是这个我希望将图像从视图发送到控制器作为Json。或者是否有其他方法上传图像而不刷新视图页面。?

2 个答案:

答案 0 :(得分:2)

您可以使用ajax发送表单...

<form id="login-form">
    <input type="file" name="photo" id="files" accept="image/*;capture=camera">
    <button type="submit" onclick="submitform()">Submit</button>
  </form>

jquery的

function submitform(){
        var postdata = $('#login-form').serialize();          
        var file = document.getElementById('files').files[0];
        var fd = new FormData();
        fd.append("files", file);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/Home/Index", false);
        xhr.send(fd);    
    }

控制器

[HttpPost]
    public JsonResult Index(FormCollection data)
    {

      if (Request.Files["files"] != null)
        {
          using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
           {
             var   Imagefile = binaryReader.ReadBytes(Request.Files["files"].ContentLength);//your image
           }
         }
    }

答案 1 :(得分:2)

将文件上传到服务器非常简单。我们需要的是一个html表单,其编码类型设置为multipart / form-data和文件输入控件。

查看:NewProduct.cshtml

<form method="post" enctype="multipart/form-data">
    <fieldset>
        <legend>New Product</legend>
    <div>
                <label>Product Name:</label>
                @Html.TextBoxFor(x => x.ProductName)
    </div>
    <div>
                <label>Product Image:</label>
               <input name="photo" id="photo" type="file">
    </div>
    <div>
                @Html.ValidationSummary()
    </div>
    <input type="submit" value="Save" />
    </fieldset>
</form>

上传的文件在Request.Files的HttpFileCollectionBase中可用。

控制器:

    [HttpPost]
    public ActionResult NewProduct()
    {
        HttpPostedFileBase image = Request.Files["photo"];
        if (ModelState.IsValid)
            {

                if (image != null && image.ContentLength > 0)
                {
                  var fileName = Path.GetFileName(image.FileName);
                  string subPath = Server.MapPath("ProductLogo");
                  bool isExists = System.IO.Directory.Exists(subPath);
                  if (!isExists)
                    System.IO.Directory.CreateDirectory(subPath);
                  var path = Path.Combine(subPath+"\\", fileName);
                  if (System.IO.File.Exists(path))
                  {
                      var nfile = DateTime.Now.ToString() + "_" + fileName;
                      path = Path.Combine(subPath+"\\", nfile);

                  }
                  file.SaveAs(path);
                  return RedirectToAction("List", "Product");
                }
                else
                {
                   ModelState.AddModelError("", "Please Select an image");
                   return View();
                }
           }
          else
          {         
             return View();
          }  
      }