Sefa
Sefa

Reputation: 8992

Serve a file using mvc web api

I want to serve a file using MVC Web Api. Here is my controller

public HttpResponseMessage GetSupplierExcel(string supplierName)
{
    var filePath = GetFileName(supplierName);

    var stream = new FileStream(filePath, FileMode.Open);
    var result = new HttpResponseMessage();

    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentLength = stream.Length;
    result.Content.Headers.ContentDisposition.FileName = fileName;

    return result;
}

Response from this action is

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Content-Type: application/octet-stream Content-Disposition: attachment; filename=abc.xlsx Content-Length: 7934 }

And there is no file being downloaded.

I'm also unable to download stream from my client using HttpClient. There is no stream, just the response string.

Upvotes: 1

Views: 928

Answers (2)

Cihan Uygun
Cihan Uygun

Reputation: 2138

Sorry for wrong information, I did not notice your api question correctly and assume you are trying to return data from mvc action. I have modified my answer according to your question. Please can you check the code below;

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public HttpResponseMessage Get(int id)
    {
        WebClient webClient = new WebClient();
        byte[] pdfContent = webClient.DownloadData("http://www.bodossaki.gr/userfiles/file/dummy.pdf");
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        string fileName = Path.GetFileName("http://www.bodossaki.gr/userfiles/file/dummy.pdf");

        result.Content = new ByteArrayContent(pdfContent);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = fileName;
        return result;
    }

    // POST api/values
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}

Upvotes: 1

John Ephraim Tugado
John Ephraim Tugado

Reputation: 765

Try using return File()

Example:

public async Task<ActionResult> GetImage(Guid id, string random = null)
    {
        string serviceBaseUrl = Utils.GetServiceBaseUrl();
        Uri url = new Uri(string.Format("{0}{1}?id={2}", serviceBaseUrl, "api/Image", id));

        HttpResponseMessage response = await JET.Utilities.Http.SendGetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            ImageResponseModel imageResponse = JsonConvert.DeserializeObject<ImageResponseModel>(await response.Content.ReadAsStringAsync());
            System.Drawing.Image displayImage = null;

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageResponse.Single.Content))
            {
                displayImage = System.Drawing.Image.FromStream(stream);
            }

            byte[] imageBytes = ImageToByte(displayImage);

            return File(imageBytes, string.Format("image/{0}", "Png"));
        }

        return RedirectToAction("Index", "Home");
    }

Upvotes: 2

Related Questions