2015-06-24 2 views
0

Я хочу загрузить и просмотреть pdf-файл в браузере одним щелчком мыши. как загружать, так и просматривать код работает на отдельных страницах , но он не работает одновременно при нажатии кнопки HttpContext.Current. Ответ любое предложение, как я могу справиться с этимC# Загрузить и просмотреть pdf-файл

ниже код

public static void DownloadFile(string filePath) 
{ 
    try { 
     HttpContext.Current.Response.ContentType = "application/octet-stream"; 
     HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + System.IO.Path.GetFileName(filePath) + "\""); 
     HttpContext.Current.Response.Clear(); 
     HttpContext.Current.Response.WriteFile(filePath); 
     HttpContext.Current.Response.End(); 

    } catch (Exception ex) { 
    } 

} 


public static void ViewFile(string filePath) 
{ 
    WebClient User = new WebClient(); 
    Byte[] FileBuffer = User.DownloadData(filePath); 

    if (FileBuffer != null) { 
     HttpContext.Current.Response.Clear(); 
     HttpContext.Current.Response.ContentType = "application/pdf"; 
     HttpContext.Current.Response.AddHeader("content-length", FileBuffer.Length.ToString()); 
     HttpContext.Current.Response.BinaryWrite(FileBuffer); 
     HttpContext.Current.Response.End(); 
    } 
    DownloadFile(filePath); 
} 
+0

Одно решение не должно состоять из двух страниц. Поток загружает и записывает в текущий выходной буфер страницы. Во-вторых, записывайте файл временно на сервер, а затем открывайте его на второй странице. – Amit

+0

@ Приходите, чтобы это сделать? – Mike

+0

Сначала скажите, файл, который вы загружаете, находится на вашем локальном компьютере или удаленном компьютере? – Amit

ответ

0

Что-то вроде этого -

Если вы хотите, чтобы загрузить и открытый сервер фи le call SendFiletoBrowser. Если вы хотите, чтобы удаленный файл был загружен и отображен в браузере, вызовите метод OpenRemoteFileInBrowser.

public void SendFiletoBrowser(string path,string fileName) 
    { 
     try 
     { 
      MemoryStream ms = new MemoryStream(); 
      using (FileStream fs = File.OpenRead(Server.MapPath(path))) 
      { 
       fs.CopyTo(ms); 
      } 
      ms.Position = 0; 
      OpenInBrowser(ms, fileName); 
     } 
     catch (Exception) 
     { 

      throw; 
     } 


    } 

    public void OpenRemoteFileInBrowser(Uri destinationUrl, string fileName) 
    { 
     try 
     { 
      WebClient wc = new WebClient(); 
      using (MemoryStream stream = new MemoryStream(wc.DownloadData(destinationUrl.ToString()))) 
      { 
       OpenInBrowser(stream, fileName); 
      } 
     } 
     catch (Exception) 
     { 

      throw; 
     } 

    } 

    private void OpenInBrowser(MemoryStream stream, string fileName) 
    { 

     byte[] buffer = new byte[4 * 1024]; 
     int bytesRead; 
     bytesRead = stream.Read(buffer, 0, buffer.Length); 

     Response.Buffer = false; 
     Response.BufferOutput = false; 
     Response.Clear(); 
     Response.ContentType = "application/octet-stream"; 
     Response.AppendHeader("Content-Disposition", "inline; filename=" + fileName); 
     if (stream.Length != -1) 
      Response.AppendHeader("Content-Length", stream.Length.ToString()); 

     while (bytesRead > 0 && Response.IsClientConnected) 
     { 
      Response.OutputStream.Write(buffer, 0, bytesRead); 
      bytesRead = stream.Read(buffer, 0, buffer.Length); 
     } 

    } 
Смежные вопросы