简体   繁体   中英

asp.net let user download file with save dialog

I am having some problems with downloading files with the save dialog.

My code executes with no errors but no save dialog shows up. Not in FF, not in chrome and not in IE. The attachment can have the following extensions: .jpg,.jpeg,.png,.bmp,.pdf,.txt,.docx . That's why I use Response.ContentType = "application/octet-stream"; (see in code below).

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

The file exists after executing the WriteAllBytes(string path, byte[] bytearray) method. If I navigate to the webPath in my code, I can also see the file in the browser (see code below).

        Response.Redirect(webPath);

What could I be doing wrong?

Many thanks.

Try this

Response.Flush(); before the Response.End();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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