使用mvc web api提供文件

时间:2016-01-27 08:39:55

标签: c# asp.net-mvc

我想使用MVC Web Api提供文件。这是我的控制器

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;
}

此操作的响应是

  

StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:   System.Net.Http.StreamContent,Headers:{Content-Type:   application / octet-stream内容 - 处理:附件;   filename = abc.xlsx内容长度:7934}

并且没有下载文件。

我也无法使用HttpClient从我的客户端下载流。没有流,只有响应字符串。

2 个答案:

答案 0 :(得分:1)

对于错误的信息感到抱歉,我没有正确注意到你的api问题,并假设你正试图从mvc动作返回数据。我根据你的问题修改了我的答案。请检查下面的代码;

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

答案 1 :(得分:1)

尝试使用return File()

示例:

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");
    }