Inicio > Programacion > ¿Cómo descargar sólo una parte de un archivo de un sitio web?

¿Cómo descargar sólo una parte de un archivo de un sitio web?

lunes, 29 de enero de 2024 Dejar un comentario Ir a comentarios

A veces, tenemos que descargar los datos desde un archivo alojado en un sitio web y es posible que tengamos sólo una parte, no la totalidad. Vamos a revisar un código que puede descargar una sección o una porción de un archivo. El único requisito para garantizar el éxito de la operación es que el servidor remoto soporte la aceptación de las solicitudes de rango para un recurso.


Código VB.NET:

 ' Beginning of the file fragment
 Dim FirstByte As Integer = 500
 ' End of the file fragment
 Dim LastByte As Integer = 999
 Dim req As HttpWebRequest = HttpWebRequest.Create("http://www.mywebsite.com/myfile.ext")
 ' Add the special header that defines the beginning and the end of the file fragment
 req.AddRange("bytes", FirstByte, LastByte)
 Dim res As HttpWebResponse = req.GetResponse()
 ' Check if the server support files fragments download
 If Not res.Headers.AllKeys.Contains("Accept-Ranges") Then
    MsgBox("The server doesn't support files fragments download!")
 End If
 Dim strm As IO.Stream = res.GetResponseStream()
 Dim i As Integer
 Dim buf(1024) As Byte
 While True
    i = strm.Read(buf, 0, 1024)
    ' Work with the buffer content
    If i <= 0 Then Exit While
 End While
 strm.Close()
 res.Close()

Código C#:

// The beginning of the file fragment to download
int firstByte = 500;
// The end of the file fragment to download
int lastByte = 999;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@"http://mywebsite.com/myfile.ext");
//  Add the special header that defines the beginning and the end of the file fragment
req.AddRange("bytes", firstByte, lastByte);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
// Check if the server support files fragments download
bool found = false;
foreach(string s in res.Headers.AllKeys) {
   if(s == "Accept-Ranges") {
      found = true;
      break;
   }
}
if(!found) {
   MessageBox.Show("The server doesn't support files fragments download!");
}
System.IO.Stream strm = res.GetResponseStream();
int i = 0;
byte[] buf = new byte[1024];
while(true) {
   i = strm.Read(buf, 0, 1024);
   // Work with the buffer content
   if(i <= 0) break;
}
strm.Close();
res.Close();

El código anterior es muy simple, lo nuevo es la llamada de la función AddRange  que añade nuestra cabecera especial para informar al servidor remoto que queremos descargar el fragmento especificado que comienza en el valor firstByte y termina en valor lastByte.
Cuando el servidor remoto recibe nuestra petición, tendremos que comprobar que podemos descargar el fragmento de archivo, al verificar que los encabezados de respuesta contenga la cabecera Accept-Ranges.
Si el encabezado Accept-Ranges no existe, la secuencia de respuesta representa el archivo completo y no sólo el fragmento que necesitamos.

Comparte y diviertete:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • BarraPunto
  • Bitacoras.com
  • BlinkList
  • Blogosphere
  • Live
  • Meneame
  • MSN Reporter
  • MySpace
  • RSS
  • Suggest to Techmeme via Twitter
  • Technorati
  • LinkedIn
  • email
  • FriendFeed
  • PDF
  • Reddit
  • Wikio IT
  • Add to favorites
  • blogmarks
Categories: Programacion Tags: , , , , ,
Top Footer