简体   繁体   中英

Open HttpResponse in a new tab

I have the following case. I am creating a filestream from a pdf file. after the reponse the generated PDF will be opened in the same tab to print, save etc.

The question is: HOW DO I CHANGE THIS CODE SO IT WILL OPEN IN A NEW TAB (OR WINDOW)?

string filepath = String.Format(*Path to file*);            
string filename = *Filename*;

            try
            {
                FileStream fs = new FileStream(filepath, FileMode.Open);
                MemoryStream ms = new MemoryStream();
                fs.CopyTo(ms);
                var docLength = fs.Length;
                fs.Close();

                WebClient req = new WebClient();
                HttpResponse response = HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();
                response.BufferOutput = true;
                Response.ContentType = "Application/pdf";
                response.AddHeader("content-disposition", "inline; filename=" + filename);
                response.AddHeader("Content-Length", docLength.ToString());

                //response.Write("<script>");
                //response.Write("window.open('" + filepath + "',_newtab');");
                //response.Write("</script>");

                byte[] data = req.DownloadData(filepath);
                response.BinaryWrite(data);
            }
            catch (Exception ex)
            {
                // Here I log the exception to a text file. 
            }
            finally
            {
                HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
                HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
                HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
            }

I have tried several options, but still not found a solution that works for me. Can someone help me with this. This function is not directly triggered by a button.

the button triggers another method which generates some other stuff and after that it triggers the method described above.

Response.Write("<script>");
Response.Write("window.open('../LOCATION/pages/FILENAME.pdf', '_newtab');");
Response.Write("</script>");

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