使用AJAX 400错误

时间:2017-09-13 15:06:45

标签: c# ajax upload asp.net-web-api2

我正在尝试使用此处提供的答案: Upload File Using WebAPI Ajax

但我一直收到400 (Bad Request)错误。

我一直在提交pdf文件,但我一直收到这个错误...

我做错了什么? ( 仅供参考我没有使用MVC

我的代码:

CSHTML(使用Razor语法)

@{
   Layout = "~/_SiteLayout.cshtml";
}

    <label>Enter File</label>
    <input type="file" name="UploadFile" id="datasheet_uploadfile" class="" accept="application/pdf"/>


<script>
$(document).ready(function() {
    $('#datasheet_uploadfile').change(function() {          
        var data = new FormData();
        var file = this.files;

        data.append('file', file);


        $.ajax({
            url: '/api/file',
            processData: false,
            contentType: false,
            data: data,
            type: 'POST'
        }).done(function(result) {
            alert(result);
        }).fail(function(a, b, c) {
            console.log(a, b, c);
        });

    });

});
</script>

我的WebAPI控制器

FileController.cs

public class FileController : ApiController
{

   // POST api/<controller>
   public HttpResponseMessage Post()
   {
       HttpResponseMessage result = null;
       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];
               int hasheddate = DateTime.Now.GetHashCode();
               //Good to use an updated name always, since many can use the same file name to upload.
               string changed_name = hasheddate.ToString() + "_" + postedFile.FileName;

               var filePath = HttpContext.Current.Server.MapPath("~/Content/stuff/" + changed_name);
               postedFile.SaveAs(filePath); // save the file to a folder "Images" in the root of your app

               changed_name = @"~\Content\stuff\" + changed_name; //store this complete path to database
               docfiles.Add(changed_name);

           }
           result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
       }
       else
       {
           result = Request.CreateResponse(HttpStatusCode.BadRequest);
       }

       return result;
    }

}

1 个答案:

答案 0 :(得分:1)

使用以下代码上传文件

 $(document).ready(function () {
   $('#datasheet_uploadfile').change(function () {
     var data = new FormData();
     data.append("file", this.files[0]);