2017-06-06 48 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