1

I Need to create a section to upload files directly to the database as Binary data, my portal is built with AngujarJS and Post to my web API

Does anyone have any examples or give me an Idea how to approach this: upload and download this files, from the c# perspective? i have built my db and 3 stored procedures, InsertDocuments, GetDocuments and GetDocument

user3376642
  • 535
  • 2
  • 8
  • 18
  • The examples are available on internet. Did you try there? – Chetan Apr 23 '18 at 23:44
  • The base64 encoding of `Content-Type: multipart/form-data` adds an extra 33% overhead. If the server supports it, [it is more efficient to send the files directly](https://stackoverflow.com/a/45599921/5535245). – georgeawg Apr 24 '18 at 03:37

1 Answers1

0

From AngularJS side you need to post your data as FormData() and append your files to this form.

HTML

<input type="file" id="inputFile" name="inputFile" >

JS

var formData = new FormData();
var selectedFiles = $("#inputFile").get(0).files
formData.append('DocumentFile', selectedFiles[0]);

$http.post(serviceUrl, formData, {
    headers: {
        'Content-Type': undefined
    }
}).then(function successCallback(response) {
    // on success
}, function errorCallback(response) {
   // on error
});

And from Web API side you can get these files from HttpContext.Current.Request.Files

[HttpPost]
public IHttpActionResult AddFile()
{
    var request = HttpContext.Current.Request;

    if (request.Files.Count > 0)
    {
        for (int i = 0; i < request.Files.Count; i++)
        {
            Stream stampStream = request.Files[i].InputStream;
            Byte[] stampBytes = new Byte[stampStream.Length];
            // Save only file name to your database
        }
    }

    return Ok();
}
ElasticCode
  • 7,311
  • 2
  • 34
  • 45
  • The base64 encoding of `Content-Type: multipart/form-data` adds an extra 33% overhead. If the server supports it, [it is more efficient to send the files directly](https://stackoverflow.com/a/45599921/5535245). – georgeawg Apr 24 '18 at 03:36