繁体   English   中英

将文件下载到客户端浏览器

[英]Download a file to a clients browser

我正在尝试下载文件并通过 URL 使其显示在客户端 PC 上。

当我使用Response.BinaryWrite我只是收到此错误:

在此处输入图片说明

我已经确认类型正确并且数组中有数据,所以我不确定我哪里出错了,希望有人能提供帮助!

仅我的响应代码:

Response.Clear();
Response.AddHeader("Content-Length", ms.Length.ToString());
Response.ContentType = contentType;
Response.AddHeader("Content-Disposition", "attachment; filename=test.png");
Response.BinaryWrite(buffer);
//Also tried: Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.Flush();
Response.End();
//Also tried this: HttpContext.Current.ApplicationInstance.CompleteRequest();

我的完整代码:

    private bool imageDownloadTesting(string imgurl, string filename)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://upload.wikimedia.org/wikipedia/commons/4/42/Cute-Ball-Go-icon.png");
        request.Method = "GET";

        HttpWebResponse response = null;

        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }
        catch
        {
            response = null;
            return false;
        }

        if (response != null && response.StatusCode == HttpStatusCode.OK)
        {
            string contentType = response.ContentType;
            Stream receiveStream = response.GetResponseStream();

            byte[] buffer = null;
            using (receiveStream)
                using (MemoryStream ms = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        byte[] buf = new byte[1024];
                        count = receiveStream.Read(buf, 0, 1024);
                        ms.Write(buf, 0, count);
                    } while (receiveStream.CanRead && count > 0);
                    buffer = ms.ToArray();

                Response.Clear();
                Response.AddHeader("Content-Length", ms.Length.ToString());
                Response.ContentType = contentType;
                Response.AddHeader("Content-Disposition", "attachment; filename=test.png");
                Response.BinaryWrite(buffer);
                //Or this Response.OutputStream.Write(buffer, 0, buffer.Length);
                Response.Flush();
                Response.End();
            }

            return true;
        }
        else
        {
            return false;
        }
    }

这是我的内容类型:

在此处输入图片说明

我真的很困惑我做错了什么,所以任何帮助都将不胜感激!

暂无
暂无

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

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