用ajax MVC上传图像 [英] uploading image with ajax MVC

查看:150
本文介绍了用ajax MVC上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试在数据库中包含图像时,在向数据库中创建新对象时遇到问题.

I'm having issue creating new object into my database when I'm trying to include image within it.

我的模特:

    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').click(函数(e){

My Ajax post code: $('#addNewDog').click(function (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保存到数据库中的映像.

My img always comes null.. I searched all over the internet and didn't figure it out. the goal is to save the PATH to my image in my database.

推荐答案

首先定义模型

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);
    });
});

这篇关于用ajax MVC上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆