2009-11-06 11 views
5

Estoy tratando de enviar un archivo en fragmentos a un HttpHandler pero cuando recibo la solicitud en el HttpContext, el inputStream está vacío.Enviando archivo en fragmentos a HttpHandler

Así que una: al enviar No estoy seguro de si mi HttpWebRequest es válida y B: mientras recibe No estoy seguro de cómo recuperar la corriente en el HttpContext

Cualquier ayuda muy apreciada!

Este como me gano la solicitud del código de cliente:

private void Post(byte[] bytes) 
    { 
     HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:2977/Upload"); 
     req.Method = "POST"; 
     req.ContentType = "application/x-www-form-urlencoded"; 
     req.SendChunked = true; 
     req.Timeout = 400000; 
     req.ContentLength = bytes.Length; 
     req.KeepAlive = true; 

     using (Stream s = req.GetRequestStream()) 
     { 
      s.Write(bytes, 0, bytes.Length); 
      s.Close(); 
     } 

     HttpWebResponse res = (HttpWebResponse)req.GetResponse(); 
    } 

esto es cómo manejar la solicitud en el HttpHandler:

public void ProcessRequest(HttpContext context) 
    { 
     Stream chunk = context.Request.InputStream; //it's empty! 
     FileStream output = new FileStream("C:\\Temp\\myTempFile.tmp", FileMode.Append); 

     //simple method to append each chunk to the temp file 
     CopyStream(chunk, output); 
    } 
+0

¿Qué CopyStream hacer? Intente usar un StreamReader y lea context.Request.TotalBytes bytes desde él. – configurator

Respuesta

3

sospecho que podría ser confuso que se va a cargar se como forma-codificada. pero eso no es lo que estás enviando (a menos que estés pasando por alto algo). ¿Es ese tipo MIME realmente correcto?

¿Qué tan grande son los datos? ¿Necesitas subir en trozos? A algunos servidores puede no gustarles esto en una sola solicitud; Estaría tentado de utilizar múltiples solicitudes simples a través del WebClient.UploadData.

+0

Estoy enviando un archivo. Los datos pueden ser grandes, por eso quiero enviarlos en pedazos. también el código del cliente necesita saber el estado de la transferencia (para una barra de carga) – teebot

+0

Yup WebClient.UploadData hizo el truco! Gracias Marc Gravell! – teebot

0

intenté con la misma idea y logré enviar archivos a través de httpwebrequest. Consulte el siguiente ejemplo de código

private void ChunkRequest(string fileName,byte[] buffer) 


{ 
//Request url, Method=post Length and data. 
string requestURL = "http://localhost:63654/hello.ashx"; 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURL); 
request.Method = "POST"; 
request.ContentType = "application/x-www-form-urlencoded"; 

// Chunk(buffer) is converted to Base64 string that will be convert to Bytes on the handler. 
string requestParameters = @"fileName=" + fileName + 
"&data=" + HttpUtility.UrlEncode(Convert.ToBase64String(buffer)); 

// finally whole request will be converted to bytes that will be transferred to HttpHandler 
byte[] byteData = Encoding.UTF8.GetBytes(requestParameters); 

request.ContentLength = byteData.Length; 

Stream writer = request.GetRequestStream(); 
writer.Write(byteData, 0, byteData.Length); 
writer.Close(); 
// here we will receive the response from HttpHandler 
StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()); 
string strResponse = stIn.ReadToEnd(); 
stIn.Close(); 
} 

he blogged sobre él, se ve el post entero HttpHandler/HttpWebRequest aquí http://aspilham.blogspot.com/2011/03/file-uploading-in-chunks-using.html espero que esto ayudará

Cuestiones relacionadas