2017-08-26 129 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 –