如何将带有其他数据的FormData文件发送到ASP.NET Web API Ajax调用

时间:2019-04-16 14:57:00

标签: jquery ajax asp.net-mvc asp.net-mvc-4 asp.net-web-api

在这个项目中,我有一种输入和文件上传的形式,ajax调用使用FormData对象将其发送到api的特定网址。 当我发送数据而没有文件上传时,它工作正常(成功)。 当我发送带有上传文件的表单时,有时返回不支持的媒体类型或使用对象Null调用Web api,我在线尝试了很多代码,但是没有用。预先感谢,这是我的代码。

html

   <form id="myForm" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="inputEmail4">Title</label>
                        <input type="text" class="form-control required" name="Title" id="Title" placeholder="Title">
                        <span id="TitleSpan" class="d-none text-danger">This field is required</span>
                    </div>
                    <div class="form-group">
                        <label for="inputAddress">Description</label>
                        <textarea type="text" class="form-control required" name="Description" id="Description" placeholder="Description..." maxlength="500" rows="5"></textarea>
                        <span id="chars">500</span> characters remaining
                        <span id="DescriptionSpan" class="d-none text-danger">This field is required</span>
                    </div>
                    <div class="form-group">
                        <label for="inputState">Priority</label>
                        <select id="Priority" name="Priority" class="form-control">
                            <option selected>Low</option>
                            <option>Medium</option>
                            <option>High</option>
                        </select>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-4">
                            <label for="City">City</label>
                            <select id="City" name="City" class="form-control">
                                <option value="Cairo" selected>Cairo</option>
                                <option value="Giza">Giza</option>
                            </select>
                        </div>
                        <img style="display:none;" src="~/Content/load.gif" id="loadingImg" />
                        <div class="form-group col-md-4">
                            <label for="Region">Region</label>
                            <input type="text" class="form-control required" name="Region" id="Region" placeholder="Region">
                            <span id="RegionSpan" class="d-none text-danger">This field is required</span>
                        </div>
                    </div>
                    <div class="form-group col-md-8">
                        <label for="exampleFormControlFile1">Upload Images</label>
                        <input type="file" class="form-control-file" value="Browse" id="PhotoPath" name="PhotoPath" accept=".png,.jpg,.jpeg" multiple>
                    </div>
                </form>

我的js

$(document).ready(function () {
    $('#btnAdd').on('click', function (e) {
            CreatePostIssuejs();
        }
    });
function CreatePostIssuejs() {
    console.log("Calling");
    console.log("i'm tracking you");
    debugger;
    var files = $("#PhotoPath").get(0).files;
    var formData = new FormData();
    for (var i = 0; i < files.length; i++) {
        formData.append("fileInput", files[i]);
    }
    formData.append('Title', $("#Title").val());
    formData.append('Description', $('#Description').val());
    formData.append('Priority', $('#Priority').val());
    formData.append('City', $('#City').val());
    formData.append('Region', $('#Region').val());
    var fileData = formData;
    $.ajax({
        url: 'api/Poset/CreatePostIssue',
        data: fileData,
        type: "POST",
        cache: false,
        contentType: false, // Not to set any content header
        processData: false, // Not to process data
        traditional: true,
        success: function (result, status, xhr) {
            debugger;
            alert(result);
            $('#myModal').modal('hide');
            $('#modalsuc').modal('show');
        },
        error: function (xhr, status, error) {
            debugger;
            alert(status);
            $('#modalwar').modal('show');
        }
    });
}

网络API

 [Route("api/Poset/CreatePostIssue")]
        [HttpPost]
        public IHttpActionResult CreatePostIssue([FromBody]PostIssueDTO postissueDTO)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string fname = null;
                    var userid = User.Identity.GetUserId();
                    var httpRequest = HttpContext.Current.Request;
                    if (httpRequest.Files.Count > 0)
                    {
                        var docfiles = new List<string>();
                        foreach (string file in httpRequest.Files)
                        {
                            var postedFile = httpRequest.Files[file];
                            fname = userid + postedFile.FileName;
                            var filePath = HttpContext.Current.Server.MapPath("~/Images/" + fname);
                            postedFile.SaveAs(filePath);
                            docfiles.Add(filePath);
                        }
                    }
                    else
                    { }
                    Post post = new Post();
                    post.PostType = "PostIssue";
                    post.AddedTime = DateTime.Now;
                    post.Title = postissueDTO.Title;
                    post.Description = postissueDTO.Description;
                    post.Priority = postissueDTO.Priority;
                    post.City = postissueDTO.City;
                    post.Region = postissueDTO.Region;
                    post.PhotoUrl = fname;
                    post.UserId = User.Identity.GetUserId();
                    _db.Posts.Add(post);
                    _db.SaveChanges();
                    return Json("success");
                }
                catch (Exception ex)
                {
                   return Json("somethimg went wrong" + ex);
                }

            }
            else
            {
               return Json("Model State wrong"); 
            }

        }

模型dto

 public class PostIssueDTO
    {
        public int Id { get; set; }
        public string PostType { get; set; }
        public DateTime AddedTime { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Priority { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public HttpPostedFileBase PhotoPath { get; set; }
        public DateTime? UpdatedOn { get; set; }
        public bool IsPinned { get; set; }
        public bool IsDelected { get; set; }
}

我希望这能像我在网上看到的那样工作。

1 个答案:

答案 0 :(得分:0)

请用以下代码替换您的js函数:

function CreatePostIssuejs() {
    console.log("Calling");
    console.log("i'm tracking you");
    debugger;

    var formData = new FormData();

    var file = document.getElementById("PhotoPath").files[0];
    formData.append("PhotoPath", file);
    formData.append('Title', $("#Title").val());
    formData.append('Description', $('#Description').val());
    formData.append('Priority', $('#Priority').val());
    formData.append('City', $('#City').val());
    formData.append('Region', $('#Region').val());
    var fileData = formData;
    $.ajax({
        url: 'api/Poset/CreatePostIssue',
        data: fileData,
        type: "POST",
        cache: false,
        contentType: false, // Not to set any content header
        processData: false, // Not to process data
        traditional: true,
        success: function (result, status, xhr) {
            debugger;
            alert(result);
            $('#myModal').modal('hide');
            $('#modalsuc').modal('show');
        },
        error: function (xhr, status, error) {
            debugger;
            alert(status);
            $('#modalwar').modal('show');
        }
    });
}

更新
也请更改此内容

 public IHttpActionResult CreatePostIssue(PostIssueDTO postissueDTO)