locked
Post request to API with variables and a file stream RRS feed

  • Question

  • User-46109667 posted

    Hi All,

    I am a newbie to web api.  I have a requirement to post a file stream with some parameters to api and return output file stream to the requester.

    I am totally blank how to do this.

    •   I have a poco class with 4 variables to pass to api.  

                       class somename

                       {

                             string var1; string var2; string var3; string var4;

                       } 

    •      I have a file converted as stream.
    •      I have a pre-designed api service project.

    How to write the new api method to receive the class variables and the file stream.

    How to return the output file as stream to the requested page code.

    Please help on this.

    Thanks in advance.

    Thursday, July 21, 2016 3:43 PM

Answers

  • User36583972 posted

    Hi RagavanB,

    How to write the new api method to receive the class variables and the file stream.

    In Web API, I suggest you upload files with HttpRequestMessage. HttpRequestMessage method allows to directly post a file from a normal HTML form and would be more flexible since you would be processing the http requests and building the responses yourself.

    You can refer the following code.

    public Task<HttpResponseMessage> Upload([FromBody]somename sm)
            {
                HttpRequestMessage request = this.Request;
                if (!request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
                }
    
                string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
                var provider = new MultipartFormDataStreamProvider(root);
    
                var task = request.Content.ReadAsMultipartAsync(provider).
                    ContinueWith<HttpResponseMessage>(o =>
                    {
                        FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);
    
                        string guid = Guid.NewGuid().ToString();
    
                        File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));
                        return new HttpResponseMessage()
                        {
                            Content = new StringContent("File uploaded.")
                        };
                    }
                );
                return task;
            }

    You can refer the following tutorial.

    Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME:

    http://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2

    How to return the output file as stream to the requested page code

    You can refer the following code to download a file.

    public HttpResponseMessage Get()
            {
                HttpResponseMessage result = null;
                var localFilePath = HttpContext.Current.Server.MapPath("~/testxmly.csv");
                if (!File.Exists(localFilePath))
                {
                    result = Request.CreateResponse(HttpStatusCode.Gone);
                }
                else
                {
                    // Serve the file to the client
                    result = Request.CreateResponse(HttpStatusCode.OK);
                    result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
                    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                    result.Content.Headers.ContentDisposition.FileName = "testxmly.csv";
                }
                return result;
            }
    
    

    Web API Thoughts 1 of 3 - Data Streaming:

    http://www.codeproject.com/Articles/838274/Web-API-Thoughts-of-Data-Streaming

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 22, 2016 2:59 AM

All replies

  • User36583972 posted

    Hi RagavanB,

    How to write the new api method to receive the class variables and the file stream.

    In Web API, I suggest you upload files with HttpRequestMessage. HttpRequestMessage method allows to directly post a file from a normal HTML form and would be more flexible since you would be processing the http requests and building the responses yourself.

    You can refer the following code.

    public Task<HttpResponseMessage> Upload([FromBody]somename sm)
            {
                HttpRequestMessage request = this.Request;
                if (!request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
                }
    
                string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
                var provider = new MultipartFormDataStreamProvider(root);
    
                var task = request.Content.ReadAsMultipartAsync(provider).
                    ContinueWith<HttpResponseMessage>(o =>
                    {
                        FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);
    
                        string guid = Guid.NewGuid().ToString();
    
                        File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));
                        return new HttpResponseMessage()
                        {
                            Content = new StringContent("File uploaded.")
                        };
                    }
                );
                return task;
            }

    You can refer the following tutorial.

    Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME:

    http://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2

    How to return the output file as stream to the requested page code

    You can refer the following code to download a file.

    public HttpResponseMessage Get()
            {
                HttpResponseMessage result = null;
                var localFilePath = HttpContext.Current.Server.MapPath("~/testxmly.csv");
                if (!File.Exists(localFilePath))
                {
                    result = Request.CreateResponse(HttpStatusCode.Gone);
                }
                else
                {
                    // Serve the file to the client
                    result = Request.CreateResponse(HttpStatusCode.OK);
                    result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
                    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                    result.Content.Headers.ContentDisposition.FileName = "testxmly.csv";
                }
                return result;
            }
    
    

    Web API Thoughts 1 of 3 - Data Streaming:

    http://www.codeproject.com/Articles/838274/Web-API-Thoughts-of-Data-Streaming

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 22, 2016 2:59 AM
  • User-46109667 posted

    Thank you Yohann Lu.

    It helped me to understand how the file stream is transferring to api from HttpClient and processing the form data using "MultipartFormDataStreamProvider"

    Friday, July 22, 2016 3:54 PM