简体   繁体   English

为什么此代码向浏览器发送0kb文件?

[英]Why is this code sending 0kb files to the browser?

here is the call... 这是电话...

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

[note that I set content length to null because I don't know it (file is on another server)] [请注意,我将内容长度设置为null,因为我不知道(文件在另一台服务器上)]

a.AssetPath is: " http://http.cdnlayer.com/account name/folder/folder/folder/asset.mp3" a.AssetPath是:“ http://http.cdnlayer.com/account name / folder / folder / folder / asset.mp3”

(fake URL for this example but in my implementation I can browse the file directly, however this attachment method is not working) (此示例的伪URL,但是在我的实现中,我可以直接浏览文件,但是此附件方法不起作用)

here is the implementation... 这是实现...

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

The file is being directly downloaded just like I want (not opened by browser) however it is NOT the file, it is simply a 0kb file with the same name. 就像我想要的那样直接下载文件(不是通过浏览器打开),但是不是文件,它只是一个同名的0kb文件。

You can only force a download as an attachment by sending the binary data out using, for example, a FileResult . 您只能通过使用例如FileResult发送二进制数据来强制将下载作为附件。 You can't force the download of a file as an attachment from a URL in this way. 您不能以此方式强制从URL下载文件作为附件。 All you're telling the browser is that what follows is an attachment, and you're giving it the URL as the name with which to save it. 您告诉浏览器的是,附件是附件,并为它提供URL作为保存它的名称。

You'd need to read in the file yourself, and write it out to the response as a series of bytes. 您需要自己读取文件,并将其作为一系列字节写到响应中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM