0

I'm trying to make use of the answer provided here: Upload File Using WebAPI Ajax

But I keep receiving a 400 (Bad Request) error.

I've been submitting a pdf file but I keep receiving this error...

What am I doing wrong? (FYI I'm not using MVC)

My code:

CSHTML (using Razor Syntax)

@{
   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>

My WebAPI Controller

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;
    }

}
bagofmilk
  • 1,492
  • 8
  • 34
  • 69

1 Answers1

1

Use the below code to upload files

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