Search This Blog

Showing posts with label HTTP Requests. Show all posts
Showing posts with label HTTP Requests. Show all posts

Monday, May 18, 2015

Clicking a button to download a server file sent as a FileContentResult via ASP.NET Web Api

Scenario:
I have a Web Api controller that returns a .csv file as a FileContentResult.
In the UI, I have a <button> element that when clicked, I want it to trigger the file download to the local computer.

Solution:
After playing a bit with ajax calls and trying to use an anchor element instead a button to follow what many web posts suggest - which is to add "data" and "chartset" attributes plus the server uri that returns the content, like

'data:text/csv;charset=UTF-8,' + encodeURI(...)
and having no success, I then switched to a different approach - also vastly suggested on the web - to simply have the browser's window.location.href attribute set to the server uri that returns the file, like


window.location.href= encodeURI(...);
The simplest and neatest solution for this problem.

Tuesday, May 12, 2015

Http Request To Upload File(s) To The Server In ASP.NET Web Api

Instructions: if you need to attach files to a http request to upload them to a server, here's basically what you need to do:

  1. In your api post method, you need to verify that the request contains files, via Request.Content.IsMimeMultipartContent
  2. Go through the files attached to the request, using HttpContext.Request.Files, casting them to HttpPostedFileBase.
  3. Now you do what you want with the files.
To test this using a http client like google's Advanced REST Client, simply mark the request as a post method, and you will be able to click a "Files" option, like the in the image below:


Usage:
            try
            {
                if (Request.Content.IsMimeMultipartContent())
                {
                    HttpFileCollectionBase files = this.UmbracoContext.HttpContext.Request.Files;
                    foreach (String uploadedFileName in files)
                    {
                        HttpPostedFileBase httpPostedFileBase = files[uploadedFileName] as HttpPostedFileBase;

                        /* do what you want with the file, here */
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }