简体   繁体   中英

Open an uploaded PDF file in new browser window/tab

In my current project, I need to open a PDF file which has been uploaded by the user. I have a file upload control and an Upload button on my aspx page. As soon as user clicks on Upload button, the file should be saved and opened in a new window.

I tried doing this using client-side function:

        <script type="text/javascript">
           function openPDF() {
           alert('The file is open.');
           window.open('Open PDF.aspx','PDF');
           return true;
          }
       </script>

But the "Open PDF.aspx" page is blank.

Open PDF.aspx.cs file looks like this:

        protected void Page_Load(object sender, EventArgs e)
        {
             string fullFileName = Session["fullFileName"].ToString();
             WebClient client = new WebClient();
             Byte[] buffer = client.DownloadData(fullFileName);

             if (buffer != null)
             {
                  Response.ContentType = "application/pdf";
                  Response.AddHeader("content-length", buffer.Length.ToString());
                  Response.BinaryWrite(buffer);
             }
       }

The full file path along with the filename is constructed in BtnUpload_Click event which is a server-side event, and is executed after the client-side function. How can I pass the full file path as a session or querystring to "Open PDF.aspx" page?

If there is any other way of accomplishing this, then please throw in your idea. Thanks!!!

You may do the following:

  • Save the uploaded file somewhere on server through ajax post call
  • After ajax call completed it may return url which shows file just uploaded
  • Then use window.open(url) (for example pdf.aspx?id=[some_id_or_name])

In your pdf.aspx you should load file locally and normally transmit it to client with appropriate headers.

evet if you pass the file name on "Open PDF.aspx" it won't work, because your upload operation will perform after "Open PDF.aspx" opened.

you can save file to server on BtnUpload_Click evet then register a client script to open saved file.

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