How to upload image in ASP.NET MVC 4 using ajax or

2019-01-13 22:55发布

I am developing a website in MVC 4, where user fill some information and save it to upload. all the information except image is being saved on server using Javascript, Json and Ajax, like given below:

$.ajax({
                    url: action,
                    type: "POST",
                    data: JSON.stringify(PostViewModel),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    beforeSend: function () {            
                    },
                    success: function (data) {
                    try{
                        alert('success');
                    }catch(err){alert(' Error: '+err);}

                    },
                    complete: function () {
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("Error occured");
                    }
            });

But Now I need to upload his image also, but I couldn't find any method that can work with this approach or any without post back.

I know putting FileUpload Control in Form tag and on press of submit button i can get image file like as given below:

 HttpPostedFileBase photo = Request.Files["photo"];
        if (photo != null)
        {
            Session["ImgPath"] = "~/Content/PostImages/" + photo.FileName;
            string path = Server.MapPath("~/Content/PostImages/");
            photo.SaveAs(path + photo.FileName);
        }

But for this method I'll have to change my approach of saving content (using Javascript, Json & Ajax) which I can't.

Please help

Thanks.

7条回答
放荡不羁爱自由
2楼-- · 2019-01-13 23:51

I also got similar Problem and after getting stuck up for many days finally this link helped me

Jquery Uploadiy with Progress Bar to be Used with MVC

and this is how i managed it

public JsonResult Upload(HttpPostedFileBase file)
{
    if (Session["myAL"] == null)
    {
        al = new ArrayList();
    }
    else
        al = (ArrayList)Session["myAL"];

    var uploadFile = file;

        if (uploadFile != null && uploadFile.ContentLength > 0)
        {
            string filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/Uploads"),
                                               Path.GetFileName(uploadFile.FileName));                    
            al.Add(filePath);
            Session["myAL"] = al;
            uploadFile.SaveAs(filePath);
        }

    var percentage = default(float);

    if (_totalCount > 0)
    {
        _uploadCount += 1;
        percentage = (_uploadCount / _totalCount) * 100;
    }

    return Json(new
    {
        Percentage = percentage
    });
}

How to Implement Attach More Files in MVC and jquery for FileUploading

查看更多
登录 后发表回答