【问题标题】:Why is this code sending 0kb files to the browser?为什么这段代码向浏览器发送 0kb 文件?
【发布时间】:2010-09-13 18:20:47
【问题描述】:

电话来了……

return new FileUriResult("application/octet-stream", a.AssetPath, null);

[请注意,我将内容长度设置为空,因为我不知道(文件在另一台服务器上)]

a.AssetPath 是:“http://http.cdnlayer.com/accountname/folder/folder/folder/asset.mp3”

(这个例子的 URL 是假的,但在我的实现中我可以直接浏览文件,但是这个附件方法不起作用)

这里是实现...

public class FileUriResult : ActionResult
    {
        private string _contentType;
        private string _fileUri;
        private long? _fileLength;

        public FileUriResult(string contentType, string fileUri, long? fileLength)
        {
            _contentType = contentType;
            _fileUri = fileUri;
            _fileLength = fileLength;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ContentType = _contentType;
            response.AddHeader("Content-Disposition", "attachment; filename=" + _fileUri);
            if(_fileLength != null)
                response.AddHeader("Content-Length", _fileLength.ToString());
        }
    }

该文件正在按我想要的方式直接下载(不是由浏览器打开),但它不是文件,它只是一个同名的 0kb 文件。

【问题讨论】:

  • 我不知道 MVC,但我的蜘蛛侠感觉你可能需要将文件的内容添加到响应中,否则它只是发送有关文件的信息,而不是文件本身(信息如文件名)

标签: c# asp.net-mvc http attachment actionresult


【解决方案1】:

您只能通过使用FileResult 发送二进制数据来强制下载作为附件。您不能以这种方式从 URL 强制下载文件作为附件。你只是告诉浏览器后面是一个附件,你给它一个 URL 作为保存它的名称。

您需要自己读取文件,并将其作为一系列字节写入响应。

【讨论】:

  • 谢谢,这很有道理,我总是对技术期望过高
猜你喜欢
  • 1970-01-01
  • 2018-01-21
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
  • 2016-07-28
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多