2017-08-26 125 views
0

我有問題創建新的對象到我的數據庫時,當我試圖包含圖像。上傳圖像與ajax MVC

我的模型:

public Dog() 

    { 

    public int Id { get; set; } 
    public string Name { get; set; } 
    public string DogImageUrl { get; set; } 

    } 

我的HTML代碼:

@if (User.Identity.IsAuthenticated) 
    { 
      <h7>New Dog</h7> 
      <input id="dogName" type="text" placeholder="dog name" /> 

       <input type="file" name="file" style="width: 100%;" /> 

       <input id="createNewDog" type="button" value="Go" /> 


      </div> 
     </div> 
    } 

我的Ajax郵編: $( '#addNewDog')點擊(函數(E){

  var imgToUpload = $("input[name=file]").get(0).files[0]; 
     var data = { 
       "Name": $('#dogName').val(), 
       "DogImageUrl ": "nullForNow", 


      }; 
      var url = "@Url.Action("NewDog", "Home")"; 
      $.ajax({ 
       url: url, 
       data: { model: data, file: Request.File[imgToUpload] }, 
       cache: false, 
       type: "POST", 
       contentType: "multipart/form-data", 
       processData: false, 
       success: function (respone) { 
        alert(respone); 
        location.reload(); 
       }, 
       error: function (reponse) { 
        alert(reponse); 
       } 
      }); 
      e.stopPropagation(); 
     }); 

我的控制器:

public ActionResult NewDog(Dog model, HttpPostedFileBase file) 
    { 


     using (var contex = new DogContext()) 
     { 
      if (User.Identity.IsAuthenticated) 
      { 

       if (file != null) 
       { 
        try 
        { 
         if (file.ContentType == "image/jpeg") 
         { 
          if (file.ContentLength < 500000) 
          { 
           string pic = System.IO.Path.GetFileName(file.FileName); 
           string path = System.IO.Path.Combine(
                 Server.MapPath("~/Content/GroupImages"), pic); 
           // file is uploaded 
           file.SaveAs(path); 
           model.DogImageUrl = path; 
          } 
         } 
        } 
        catch (Exception ex) 
        { 
         return Content(ex.ToString()); 
        } 
       } 

       contex.Dogs.Add(model); 
       contex.SaveChanges(); 
      } 
     } 

我的IMG總是零..我在互聯網上搜索,並沒有弄清楚。 目標是將PATH保存到我的數據庫中的圖像。

+0

1.您不太可能從客戶端計算機獲取實際路徑 - 瀏覽器通常會混淆實際路徑。 2.調試控制檯中是否有腳本錯誤? 3.請參閱[jQuery Ajax文件上傳](https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload)和更多[MVC特定](https://stackoverflow.com/questions/29293637/如何對追加-全設置的模型對FORMDATA和-獲得-IT-在-MVC)。 – Jasen

+0

@Jasen的想法是保存從服務器的路徑,用戶上傳圖像,它將其保存在我的服務器,我想要在「DogImageUrl」中獲取路徑 –

+0

第二個鏈接演示如何將圖像張貼得很清楚。 – Jasen

回答

0

首先定義你的模型

public class DogUpload 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public HttpPostedFileBase Image { get; set; } 
} 

那麼你的行動

[HttpPost] 
public ActionResult Upload(DogUpload model) 
{ 
    var image = model.Image; 
    var name = model.Name; 
    var fileName = image.FileName; 

    var path = Server.MapPath("~/Content/GroupImages" + fileName); 
    image.SaveAs(path); 

    // create valid url to dog image 
    // create Dog and save to database 
    var dog = dbContext.Dogs.FirstOrDefault(d => d.Id == model.Id); 
    if (dog == null) 
    { 
     dog = new Dog 
     { 
      Name = model.Name, 
      DogImageUrl = url 
     }; 
     ... 
    } 

    return Json(new { message = "Created", id = dog.Id, name = dog.Name, url = dog.DogImageUrl }); 
} 

您的看法

@using(Html.BeginForm("Upload", "Dog", FormMethod.Post, 
     new { id="dogForm", enctype="multipart/form-data" }) 
{ 
    <input type="file" name="Image" /> 
    <input type="text" name="Name" /> 
    <button type="submit">Submit</button> 
} 

的AJAX

$("#dogForm").on("submit", function(e) { 
    e.preventDefault(); 

    var form = $(this); 
    var formData = new FormData(form.get(0)); 

    $.ajax({ 
     url: form.attr("action"), 
     method: form.attr("method"), 
     data: formData, 
     processData: false, 
     contentType: false 
    }) 
    .then(function(result) { 
     console.log(result); 
    }); 
}); 
+0

我很欣賞你的答案,但我的目標是將圖像路徑(應該存儲在我的服務器中)保存在我的狗模型中,而不是更新模型時的圖像本身 –

+0

「我的圖像總是爲空」總是空? – Jasen

+0

我試圖上傳的那個:/它來到控制器null –