1

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.

2 Answers 2

2

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");
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this @John Ephraim Tugado, this actually worked. Tried swapping Stream and ByteArrayContent to no avail, I was still getting a string back, returning a File worked. Cheers!
1

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)
    {
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.