Saltar al contenido

Cargar archivos con HTTPWebrequest (multipart / form-data)

Esta es el arreglo más válida que encomtrarás dar, sin embargo mírala pausadamente y analiza si se puede adaptar a tu trabajo.

Solución:

Tomó el código anterior y lo solucionó porque arroja el Error interno del servidor 500. Hay algunos problemas con r n mal posicionados y espacios, etc. Se aplicó la refactorización con el flujo de memoria, escribiendo directamente en el flujo de solicitud. Aquí está el resultado:

    public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc) 
        log.Debug(string.Format("Uploading 0 to 1", file, url));
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("rn--" + boundary + "rn");

        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
        wr.ContentType = "multipart/form-data; boundary=" + boundary;
        wr.Method = "POST";
        wr.KeepAlive = true;
        wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

        Stream rs = wr.GetRequestStream();

        string formdataTemplate = "Content-Disposition: form-data; name="0"rnrn1";
        foreach (string key in nvc.Keys)
        
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            rs.Write(formitembytes, 0, formitembytes.Length);
        
        rs.Write(boundarybytes, 0, boundarybytes.Length);

        string headerTemplate = "Content-Disposition: form-data; name="0"; filename="1"rnContent-Type: 2rnrn";
        string header = string.Format(headerTemplate, paramName, file, contentType);
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        rs.Write(headerbytes, 0, headerbytes.Length);

        FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) 
            rs.Write(buffer, 0, bytesRead);
        
        fileStream.Close();

        byte[] trailer = System.Text.Encoding.ASCII.GetBytes("rn--" + boundary + "--rn");
        rs.Write(trailer, 0, trailer.Length);
        rs.Close();

        WebResponse wresp = null;
        try 
            wresp = wr.GetResponse();
            Stream stream2 = wresp.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);
            log.Debug(string.Format("File uploaded, server response is: 0", reader2.ReadToEnd()));
         catch(Exception ex) 
            log.Error("Error uploading file", ex);
            if(wresp != null) 
                wresp.Close();
                wresp = null;
            
         finally 
            wr = null;
        
    

y uso de muestra:

    NameValueCollection nvc = new NameValueCollection();
    nvc.Add("id", "TTR");
    nvc.Add("btn-submit-photo", "Upload");
    HttpUploadFile("http://your.server.com/upload", 
         @"C:testtest.jpg", "file", "image/jpeg", nvc);

Podría extenderse para manejar varios archivos o simplemente llamarlo varias veces para cada archivo. Sin embargo, se adapta a sus necesidades.

Estaba buscando algo como esto, que se encuentra en: http://bytes.com/groups/net-c/268661-how-upload-file-via-c-code (modificado para que sea correcto):

public static string UploadFilesToRemoteUrl(string url, string[] files, NameValueCollection formFields = null)

    string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
    request.ContentType = "multipart/form-data; boundary=" +
                            boundary;
    request.Method = "POST";
    request.KeepAlive = true;

    Stream memStream = new System.IO.MemoryStream();

    var boundarybytes = System.Text.Encoding.ASCII.GetBytes("rn--" +
                                                            boundary + "rn");
    var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("rn--" +
                                                                boundary + "--");


    string formdataTemplate = "rn--" + boundary +
                                "rnContent-Disposition: form-data; name="0";rnrn1";

    if (formFields != null)
    
        foreach (string key in formFields.Keys)
        
            string formitem = string.Format(formdataTemplate, key, formFields[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            memStream.Write(formitembytes, 0, formitembytes.Length);
        
    

    string headerTemplate =
        "Content-Disposition: form-data; name="0"; filename="1"rn" +
        "Content-Type: application/octet-streamrnrn";

    for (int i = 0; i < files.Length; i++)
    
        memStream.Write(boundarybytes, 0, boundarybytes.Length);
        var header = string.Format(headerTemplate, "uplTheFile", files[i]);
        var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

        memStream.Write(headerbytes, 0, headerbytes.Length);

        using (var fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
        
            var buffer = new byte[1024];
            var bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            
                memStream.Write(buffer, 0, bytesRead);
            
        
    

    memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
    request.ContentLength = memStream.Length;

    using (Stream requestStream = request.GetRequestStream())
    
        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
    

    using (var response = request.GetResponse())
    
        Stream stream2 = response.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);
        return reader2.ReadToEnd();
    

ACTUALIZACIÓN: Usando .NET 4.5 (o .NET 4.0 agregando el paquete Microsoft.Net.Http de NuGet) esto es posible sin código externo, extensiones y manipulación HTTP de "bajo nivel". Aquí hay un ejemplo:

// Perform the equivalent of posting a form with a filename and two files, in HTML:
// 
// // // //
private async Task UploadAsync(string url, string filename, Stream fileStream, byte [] fileBytes) // Convert each of the three inputs into HttpContent objects HttpContent stringContent = new StringContent(filename); // examples of converting both Stream and byte [] to HttpContent objects // representing input type file HttpContent fileStreamContent = new StreamContent(fileStream); HttpContent bytesContent = new ByteArrayContent(fileBytes); // Submit the form using HttpClient and // create form data as Multipart (enctype="multipart/form-data") using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) // Add the HttpContent objects to the form data // formData.Add(stringContent, "filename", "filename"); // formData.Add(fileStreamContent, "file1", "file1"); // formData.Add(bytesContent, "file2", "file2"); // Invoke the request to the server // equivalent to pressing the submit button on // a form with attributes (action="url" method="post") var response = await client.PostAsync(url, formData); // ensure the request was a success if (!response.IsSuccessStatusCode) return null; return await response.Content.ReadAsStreamAsync();

Recuerda que te permitimos valorar este escrito si chocaste tu impedimento justo a tiempo.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *