asp.net 让用户使用保存对话框下载文件

本文关键字:保存 对话框 下载 文件 net 用户 asp | 更新日期: 2023-09-27 18:34:22

我在使用保存对话框下载文件时遇到一些问题。

我的代码执行时没有错误,但没有显示保存对话框。不是在FF中,不是在chrome中,也不是在IE中。附件可以具有以下扩展名:.jpg,.jpeg,.png,.bmp,.pdf,.txt,.docx 。这就是我使用Response.ContentType = "application/octet-stream";的原因(请参阅下面的代码)。

    protected void btnDownload_OnCommand(object sender, CommandEventArgs e)
    {
        //Get the attachment to download from the webservice
        RCX.AddressAttachment attachment = ShopClient.GetAddressAttachment(ServiceContext,
            new AddressAttachmentCriteria()
            {
                Id = (string) e.CommandArgument //= AttachmentID
            });
        //Get a random filename
        var fileName = string.Format("{0}{1}", Guid.NewGuid(), attachment.FileExtension);
        //Get the physicalPath to save the file
        var physicalPath = string.Format(@"{0}'Attachments'{1}", System.AppDomain.CurrentDomain.BaseDirectory,
            fileName);
        //Get the webpath to navigate to the file
        var webPath = string.Format("{0}Attachments/{1}", Misc.BaseUrl(Request.Url), fileName);
        //Create file if not exists
        using (new FileStream(physicalPath, FileMode.OpenOrCreate))
        {
        }
        //Write bytes to file
        System.IO.File.WriteAllBytes(physicalPath, attachment.Attachment);

        var fileInfo = new FileInfo(physicalPath);
        //Try to open the save dialog, what is wrong here?
        Response.Clear();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0};", fileName));
        Response.AddHeader("Content-Length", fileInfo.Length.ToString());
        Response.WriteFile(physicalPath);
        Response.End();   
    }

执行 WriteAllBytes(string path, byte[] bytearray) 方法后,该文件存在。如果我在代码中导航到 webPath,我还可以在浏览器中看到该文件(请参阅下面的代码)。

        Response.Redirect(webPath);

我可能做错了什么?

非常感谢。

asp.net 让用户使用保存对话框下载文件

试试这个

Response.Flush();在 Response.End() 之前;