使用文件上载添加新数据

时间:2014-12-12 11:12:24

标签: javascript c# asp.net ajax

我有这个表单有两个字段,一个名字和一个图像字段。以下是表格的代码

@using (Html.BeginForm("AddNewRecipe", "Kitchen", FormMethod.Post, new { enctype = "multipart/form-data", id = "addNewRecipe", data_partitionId = Model.Id }))
{
  <input type="text" placeholder="Recipe Name" name="newRecipeName" id="newRecipeName" value="" />
  <input type="file" accept="image/*" name="newRecipeImage" id="newRecipeImage" value="" />
  <button type="submit" class="button small" id="submitnewRecipe">Add</button>
}

提交表单时,我在我的JavaScript中执行此操作,

$('form#addNewRecipe').submit(function (event) {
    event.preventDefault();
    var data = new FormData();
    var files = $('#newRecipeImage').get(0).files;
    if (files.length > 0) {
        data.append("UploadedImage", files[0]);
    }
    console.log(data); // no data is appended
});

我在这里要做的是将图像文件和名称发送到服务器,以便上传它们。有关如何做到这一点的任何见解?

我在asp.net mvc c#中寻找一个很好的解决方案。

也许我的技术不太好。我很乐意接受批评。 :)

1 个答案:

答案 0 :(得分:1)

我在我的项目(工作代码)中使用它

jquery的

var formData = new FormData();
var files = $('#newRecipeImage').get(0).files;
if (files.length > 0) {
    formData.append("img", files[0]);//files[0].name contains the file name
}
$.ajax({
   cache: false,
   type: 'POST',
   data: formData,
   processData: false,
   contentType: false,
   url: '/Sport/GetImagePreview',
   success: function(data) {
           //$("#yourImage").attr("src", "data:image/png;base64," + data.base64imgage);         
   },
   error: function (XMLHttpRequest, textStatus, errorThrown) {

   }
});

然后在控制器

 [HttpPost]
 public JsonResult GetImagePreview()
 {
     try
     {
     if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
     {
         var img = System.Web.HttpContext.Current.Request.Files["img"];//Request.FILES['img'].name contains the file name
         var ms = new MemoryStream();
         var logo = Image.FromStream(img.InputStream);
         logo = FixedSize(logo, 150, 150);
         logo.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

         return Json(new {base64imgage = Convert.ToBase64String(ms.ToArray())});
     }
     return Json("ko");
   }
   catch (Exception)
   {
      return Json("ko");
   }
 }