0

I'm looking for a solution where I can upload any file to SQL server from an AngularJS frontend to .Net Web Api 2 and straight to SQL Server Database. I've done some research and for angularjs i'm mainly looking at ng-file-upload. my problem is most of the solutions that i've looked at saves the file into a temp folder. I'm not sure if it's possible but I want it straight to an SQL server table.

I've seen some solutions where it converts the file into a byte array which can be saved to an SQL table but I'm not sure how to do this in a .NET web api 2 and from an angularjs front end. thank you in advance.

vbravo
  • 3
  • 3

1 Answers1

0

Don't save files to SQL server--that's not what it's for. See this answer: In MVC4, how do I upload a file (an image) to SQL Server that's part of my domain model? And this answer: Storing files in SQL Server


Uploading files in angular is easy. Do it like this:

Controller

$scope.uploadFile = function() {
    //get the filename from the <input type='file'>
    //angular doesn't allow attaching ngModel to file input
    var fileInput = document.getElementById("myInputId");

    //check if there's a file
    if(fileInput.files.length === 0) return;

    //you cannot send a file as JSON because json is in the string format
    //for fileuploads, you must send as a FormData() object
    //C# accepts HttpPostedFileBase as the file argument
    var file = fileInput.files[0];

    //put the file in a new formdata object
    var payload = new FormData();
    payload.append("file", file);

    //upload file to C# controller
    $http.post("path/to/C#/controller", payload, {
            //you **need** to specify these options, without them upload does not work
            transformRequest: angular.identity,
            headers: { "Content-Type": undefined }
    }).then(function(data) {
        //success
    }, function(error) {
        //error
    });
}

C#/ASP.NET

[WebMethod]
public string UploadFile(HttpPostedFileBase file) {
    //access the file object here
    var inputStream = file.InputStream;
    var fileName = Path.GetFileName(file.FileName);

    try
    {
        file.SaveAs("local/path" + fileName);
    }
    catch (IOException exc)
    {
        return "Error: " + exc.Message;
    }

    return "success";
}
Community
  • 1
  • 1
Kyle
  • 5,407
  • 6
  • 32
  • 47
  • Thank you for the reply. I tried the code you have written, but i'm getting a server error 415 (Unsupported Media type). It is not even going to my web api controller. is there anything that I might be missing? again, thank you. – vbravo Apr 25 '16 at 20:23
  • That's a server error; nothing to do with Javascript. Make sure the API controller accepts the file you're uploading. – Kyle Apr 25 '16 at 20:28