FormData无法进入服务器,我的代码出了什么问题

时间:2019-09-26 10:18:59

标签: c# ajax model-view-controller


我该怎么做才能将 FormData 发送到我的服务器,我的文件在服务器中始终为null或返回Unsupported Media status 415,我尝试解决此问题,但有现在不知道......

<form enctype="multipart/form-data" name="add_data" id="add_data" method="post" onsubmit="return false"   >
    <input type="file" multiple="multiple" name="files" value="" id="files" />
    <br />
    <input type="submit" class="btn btn-success" value="Upload">
    <br />
</form> 

这是我的html部分,然后 阿贾克斯

$('#add_data').submit(function () {
            var totalFiles; 
            totalFiles = document.getElementById("files").files[0];
            var formData = new FormData();
            formData.append("files", totalFiles);
            $.ajax({
                url: "/api/food/addfile",
                type: "Post",
                data:myData,
                contentType: false,
                processData: false,
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + token);
                },
                data:  totalFiles ,
                dataType: 'json',
                success: function () {
                    alert("success")
                },
                error: function (jqXHR, exception) {
                    if (jqXHR.status == 401) {
                       return alert("請先執行前置作業");
                    }
                    alert(jqXHR.responseText);
                }
            });
        });

和控制器

[Authorize]
    [HttpPost,Route("addfile")]
    public  IActionResult GetPicture(/*HttpPostedFileBase[] files*/)
    {
        #region test1
        //if (files != null)
        //{

        //    foreach (HttpPostedFileBase file in files)
        //    {
        //        file.SaveAs(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/upload/"), file.FileName));
        //    }
        //}
        #endregion

        #region test2

        var req = System.Web.HttpContext.Current.Request;
        if (req.Files.Count > 0)
        {
            foreach (string fileName in req.Files.Keys)
            {
                var file = req.Files["files"];
                file.SaveAs(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/upload/"), file.FileName));
            }
        }


        #endregion

        return Json(new { Status = 1 > 0 ? "SUCCESS" : "FAILS" });

所有代码,请谁能告诉我谢谢。

0 个答案:

没有答案