2016-04-12 81 views
0

我試圖上傳圖像時遇到此問題。當我點擊提交按鈕,我得到以下錯誤:clickASP MVC中的圖像上傳錯誤

當我使用withaut模式PARAM它的工作原理,但窗口不模式,並期待非常糟糕。

型號:

public partial class Prod 
{ 
    public string PName { get; set; } 
    public byte[] PFile{ get; set; } 
} 

索引視圖:

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

@Html.ActionLink(" ", "Create", "Products", null, new { data_modal = "file", id = "btnCreate", @class = "btn btn-small btn-primary pull-right fa fa-cart-plus" })

@Html.ActionLink(" ", "Create", "Products", null, new { id = "btnCreate", @class = "btn btn-small btn-primary pull-right fa fa-cart-plus" })

}

創建視圖:

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

    <div class="modal-body"> 

     <div class="form-horizontal"> 
      @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 

      <div class="form-group"> 
       @Html.LabelFor(model => model.PFile, "Plik", htmlAttributes: new { @class = "control-label col-md-3" }) 
       <div class="col-md-9"> 
        @Html.TextBoxFor(model => model.PFile, new { type = "file", name = "imageF" }) 
        @Html.ValidationMessageFor(model => model.PFile, "", new { @class = "text-danger" }) 
       </div> 
      </div> 

     </div> 

    </div> 

    <div class="modal-footer"> 
     <button class="btn" data-dismiss="modal">Anuluj</button> 
     <input class="btn btn-primary" type="submit" value="Zapisz" /> 
    </div> 
} 

控制器:

[HttpPost] 
     [AcceptVerbs(HttpVerbs.Post)] 
     [ValidateAntiForgeryToken] 
     public ActionResult Create([Bind(Exclude = "PFile")] Prod pro, HttpPostedFileBase imageF) 
     {      
      if (ModelState.IsValid) 
      { 

        if (imageF != null) 
        { 
         pro.PName= imageF.ContentType; 
         pro.PFile= new byte[imageF.ContentLength]; 
         imageF.InputStream.Read(pro.PFile, 0, imageF.ContentLength); 
        } 


        db.Prods.Add(pro); 
        db.SaveChanges(); 
        return Json(new { success = true }); 

      } 

      return PartialView("Create", pro); 
     } 

modalform.js

$(function() {

$.ajaxSetup({ cache: false }); 

$("a[data-modal]").on("click", function (e) { 

    // hide dropdown if any 
    $(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle'); 


    $('#myModalContent').load(this.href, function() { 


     $('#myModal').modal({ 
      /*backdrop: 'static',*/ 
      keyboard: true 
     }, 'show'); 

     bindForm(this); 
    }); 

    return false; 
}); 

});

function bindForm(dialog) {

$('form', dialog).submit(function() { 
    $.ajax({ 
     url: this.action, 
     type: this.method, 
     data: $(this).serialize(), 
     contentType: 'multipart/form-data', 
     success: function (result) { 
      if (result.success) { 
       $('#myModal').modal('hide'); 
       //Refresh 
       location.reload(); 
      } else { 
       $('#myModalContent').html(result); 
       bindForm(); 
      } 
     } 
    }); 
    return false; 
}); } 

請幫助解決這個問題。

+0

當您通過ajax發佈時,表單編碼類型是否會丟失? –

+0

對不起,我是begginer,我不知道你是什麼意思 – Ebasse

+0

我的意思是你添加enctype multipart/form-data到表單,但是你通過一個ajax文章提交你的文件,而我沒有看到攜帶相同編碼類型。 –

回答

0

嘗試在綁定屬性中包含HttpPostedFileBase對象的名稱。任何你沒有放在那裏的東西都會被排除在請求之外。 想要這樣:

public ActionResult Create([Bind(Exclude = "PFile", Include = "imageF")] Prod pro, HttpPostedFileBase imageF) 
+0

沒有改變。我thcink探針是在JS文件 – Ebasse

+0

對不起,我更新我的答案。您必須使用包括不包括 –

+0

而不更改。我的代碼沒有使用從.js文件中使用的data_modal參數。當我添加這個參數是錯誤空異常 – Ebasse

0

請檢查這一個。首先你不能通過ajax調用發佈文件。需要完整回發才能在服務器端發佈文件。還有一些其他技術可以處理來自Ajax調用的文件。

檢查此代碼..

控制器功能。

public ActionResult Create(Prod pro) 
    { 
     if (ModelState.IsValid) 
     { 

      if (pro.PFile != null) 
      { 
       pro.PName = pro.PFile.ContentType; 
       pro.PFileByte = new byte[pro.PFile.ContentLength]; 
       pro.PFile.InputStream.Read(pro.PFileByte, 0, pro.PFile.ContentLength); 
      } 


      //db.Prods.Add(pro); 
      //db.SaveChanges(); 
      return Json(new { success = true }); 
     } 
     return PartialView("Create", pro); 
    } 

視圖模型...

public partial class Prod 
{ 
    public string PName { get; set; } 
    public byte[] PFileByte { get; set; } 
    public HttpPostedFileBase PFile { get; set; } 
} 

刪除您的表單提交功能檢查。如果需要阿賈克斯電話,然後告訴我的意見。

+0

當我更改此代碼並提交表單時,我有錯誤空異常。獨立或模態參數與否。 請告訴我如何更改.js文件的工作? – Ebasse

+0

另一種方式是以base64string的形式在模型內部發送文件。在JavaScript中將文件讀取爲緩衝區,然後將其轉換爲base64string。您可以輕鬆將此字符串發送給控制器操作。在控制器上將此base64轉換爲緩衝區數組。如果您不使用ajax調用,上面的代碼必須工作。 – Saif

+0

你能給我一些代碼嗎? – Ebasse

0

對不起,我的壞英語提前!

使用此表單,您不需要使用ajax。確保有一個隱藏的PName輸入,或者發送給控制器的模型無效。我很確定你需要有一個ID來添加數據到你的數據庫中,所以把它添加到你的模型中,並確保你的變量pro有一個有效的id(一個數字)。

試試這個讓你的控制器上傳一個文件。確保改變你所需要的返回線! :

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create([Bind(Exclude = "PFile,PName")] Prod pro) 
{      
    if (ModelState.IsValid) 
    {  
     try 
     { 
      if (Request.Files[0] != null && Request.Files[0].ContentLength > 0) 
      { 
       byte[] tmp = null; 
       using (var bin = new BinaryReader(Request.Files[0].InputStream)) 
       { 
        tmp = bin.ReadBytes(Request.Files[0].ContentLength); 
       } 
       pro.PName = Request.Files[0].ContentType; 
       pro.PFile = tmp; 
      } 
     } 
     catch { 
      throw new Exception("There is no file to upload."); 
      // TODO Change the exception to this if your want your PFile and PName to be null if there's no file. 
      // pro.PName = ""; 
      // pro.PFile = null; 
     } 
     db.Prods.Add(pro); 
     db.SaveChanges(); 
     return RedirectToAction("Index", "Whatever"); 
    } 
    return PartialView("Create", pro); 
} 
+0

它只有當我打開時沒有模態形式就像我的代碼。 當我使用模式形式參數,我有這個錯誤: 索引超出範圍。必須是非負數且小於集合的大小。 – Ebasse

+0

@Ebasse好吧,所以嘗試用ajax發送它,但使用formData!它是一種通過ajax將文件發送到C#方法的好方法! – AlwaysBeShels