【问题标题】:Serve a file using mvc web api使用 mvc web api 提供文件
【发布时间】:2016-05-04 02:39:42
【问题描述】:

我想使用 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,标头:{ 内容类型: application/octet-stream Content-Disposition:附件; 文件名=abc.xlsx 内容长度:7934 }

并且没有正在下载的文件。

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

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案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");
        }
    

    【讨论】:

    • 感谢@John Ephraim Tugado,这确实有效。尝试交换 Stream 和 ByteArrayContent 无济于事,我仍然得到一个字符串,返回一个文件工作。干杯!
    【解决方案2】:

    抱歉信息有误,我没有正确注意到您的 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)
        {
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-02
      • 2018-06-30
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多