2017-06-06 45 views
1

我是新的asp网络,我有一个图像列表,我想通过JavaScript发送到控制器。ASP NET MVC RAZOR上传多个图片FileList

我正在使用FileList,这里是一个例子。 .Create.cshtml

<div class="form-group"> 
    @Html.LabelFor(model => model.description, "Escolha as Imagens", htmlAttributes: new { @class = "control-label col-md-2" }) 
    <input id="files" type="file" name="files[]" /> 
    <br> 
    <div id="preview"></div> 
</div> 
@section Scripts{ 
    <script type="text/javascript"> 
     function handleFileSelect(evt) { 

      var files = evt.target.files; 
      var f = files[0]; 
      //kiem tra co fai file anh 
      if (f.type.match('image.*')) { 
       var reader = new FileReader(); 

       reader.onload = (function(theFile) { 
        return function(e) { 
         var span = document.createElement('span'); 
         span.innerHTML = [ 
          '<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), 
          '"/><span class="remove_img_preview"></span>' 
         ].join(''); 
         document.getElementById('preview').insertBefore(span, null); 
        }; 
       })(f); 

       reader.readAsDataURL(f); 
      } 
     } 

     $('#files').change(function(evt) { 
      handleFileSelect(evt); 
     }); 
     $('#preview').on('click', 
      '.remove_img_preview', 
      function() { 
       $(this).parent('span').remove(); 
      }); 

     $('#btnSave').click(function() { 

      $.ajax({ 
       url: '/Dishes/Create', 
       data: { files: files }, 
       type: "POST", 
       cache: false, 
       datatype: "html", 
       success: function(data) { 
        console.log(data); 
       }, 
       error: function(jqXhr, textStatus, errorThrown) { 
        //do your own thing 
        alert("fail"); 
       } 
      }); 
     }); 

    </script> 
} 
</fieldset> 
<div class="form-group"> 
    <div class="footer text-center"> 
     <button class="btn btn-fill btn-info" name="btnSave" id="btnSave">Inserir novo</button> 
    </div> 
</div> 

Controller.cs

public ActionResult Create() 
    { 
     ViewBag.idTypeDish = new SelectList(db.TypeDish, "idTypeDish", "name"); 
     return View(); 
    } 



    // POST: Dishes/Create 
    [HttpPost] 
    public ActionResult Create(IEnumerable<HttpPostedFileBase> files) 
    { 


     return View(); 

    } 

在控制器,文件总是空。 我正在使用该示例,http://jsfiddle.net/Lwczca6p/1/,我只是适应了我的项目。

+0

你可能不需要这么做,但是如果你打算允许多个文件上传,那么你需要添加'multiple =“多个“输入到你的文件中(假设你使用的是html5 – Ortund

+0

@Ortund Ya我知道你的意思,但是如果他选择了2张图片,那么他会选择另一张图片,会发生什么?我有一个FileList, t发送FileList到控制器? – kroz

+0

@Outund我使用所有的代码,因为在上传到服务器之前,用户可以预览图像并删除它,如果他想要的话。 – kroz

回答

2

你有几个问题。首先,您尝试在您的AJAX中使用files,但该变量是在另一个函数的范围内定义的(即您在此处无法访问它)。其次,当使用jQuery的$.ajax来进行文件上传时,您需要将processData选项设置为false。下面是我如何处理它:

$('#MyForm').on('submit', function (e) { 
    e.preventDefault(); 
    var formData = new FormData(this); // `this` is the form instance 
    $.ajax({ 
     url: '/path/to/handler', 
     type: 'POST', 
     data: formData, 
     processData: false, 
     contentType: 'multipart/form-data', 
     success: function (data, textStatus, jqXHR) { 
      // do something on success 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 
      // do something on error 
     } 
    }); 
}); 
+0

嘿,谢谢你的回答,但它如何在控制器上工作?我会有什么参数呢?我以前从未使用FormData。 – kroz

0

试试这个,首先要建立您的视图模型:

public class FileModel 
{ 
    [Required(ErrorMessage ="Please select file.")] 
    [Display(Name ="Browse File")] 
    public HttpPostedFileBase[] files { get; set; } 

} 

然后,编辑视图这个(使上传你需要把多个=“多”在你的元素很多文件):

@model Models.FileModel 

@using (Html.BeginForm("Create", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.AntiForgeryToken() 

    <div class="form-horizontal"> 
     <hr /> 
     @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 
     <div class="form-group"> 
      @Html.LabelFor(model => model.files, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.TextBoxFor(model => model.files, "", new { @type = "file", @multiple = "multiple" }) 
       @Html.ValidationMessageFor(model => model.files, "", new { @class = "text-danger" }) 
      </div> 
     </div> 
     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <input type="submit" value="Upload" class="btn btn-primary" /> 
      </div> 
     </div> 

     </div> 
} 
+0

嗯,谢谢你的回答!真的是我想要的......我希望能够逐个选择图像,并最终将文件数组发送到控制器。 – kroz

+0

哦,好的。你有没有试过使用Dropzone? http://www.dropzonejs.com/我用它一次与asp.net mvc。如果你愿意,我可以给你一个例子。 –

+0

不,我从来没有使用过dropzone,但是从我读的内容立即上传到服务器,这不是我想要的...我希望能够添加和删除图像,然后在产品注册时上传。但是,如果你不介意的话,我会想要一个例子。 – kroz