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

}

1 Answer 1

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]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.