如何通过Jquery Ajax将图像和一些数据作为参数传递给Web API Controller

时间:2018-10-06 10:34:25

标签: jquery ajax asp.net-core-webapi

我正在尝试通过jquery ajax将topicmedia和图像文件传递给Web api后控制器。但无法完成此任务,我从最近2天开始尝试此操作。请任何人告诉这个。

Ajax Code Here

Web API Controller Action Here i want to get data and image

$('#add').click(function () {
var topicmedia = {"topicid":"","createon":""};
            topicmedia.topicid = 1;
            topicmedia.createon = $('#txtCreateOn').val();
            var data = new FormData();
            var file = $("#img").get(0).files;
            data.append("file", file);
            debugger;
            $.ajax({     
                url: 'http://localhost:4728/api/TopicMedias',
                method: 'POST',
                contentType: 'multipart/form-data',
               // processData: false,
                data: JSON.stringify(topicmedia, file),
                dataType: 'json',
                success: function () {
                    $('#successfullModel').modal('show');
                }
      });
  });

这是Web API的代码,我想获取2个参数topicmedia,其中包含topicid和createon数据以及文件参数接收图像

  public IHttpActionResult PostTopicMedia(TopicMedia topicMedia, HttpPostedFile files)
    {
        return null;
    }

}

在通过Web api操作获取图像和数据之后,我想将图像保存在文件夹中,并将其他数据和图像路径保存在具有数据路径,topicid和createOn字段的数据库表topicmedia中。

1 个答案:

答案 0 :(得分:1)

public async Task<HttpResponseMessage> PostImage()
{
    Dictionary<string, object> dict = new Dictionary<string, object>();
    var httpRequest = HttpContext.Current.Request;
    foreach (string file in httpRequest.Files)
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
        var postedFile = httpRequest.Files[file];
        if (postedFile != null && postedFile.ContentLength > 0)
        {
            IList<string> AllowedFileExtensions = new List<string>{".jpg", ".png"};
            var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
            var extension = ext.ToLower();
            if (!AllowedFileExtensions.Contains(extension))
            {
                var message = string.Format("Please Upload image of type .jpg, .png.");
                dict.Add("error", message);
                return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
            }
            else
            {
                var filePath = HttpContext.Current.Server.MapPath("~/yourDirectory/" + postedFile.FileName + extension);
                postedFile.SaveAs(filePath);
            }
        }

        var successMsg = string.Format("Image Updated Successfully.");
        return Request.CreateErrorResponse(HttpStatusCode.Created, successMsg);
    }

    var res = string.Format("Please Upload a image.");
    dict.Add("error", res);
    return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}