1

Following on from my post..

Saving an image from HTTP POST (Not using FileUpload Control). Where I kind of came to the assumption that I could just use Request.Files..

To test the saving functionality, i'm now looking at sending an image via an HTTP Post by crafting this HTTP Post dynamically in the code behind and not using a FileUpload Control.

It is touched upon here..

Send a file via HTTP POST with C#

But, i'm looking for a more complete sample and one that ensures that other POST variables are maintained.

In fact this one might help..

Multipart forms from C# client

UPDATE : Sorry.. Question is..

How do I send an image to a url via HTTP Post (without file upload control) along with other POST variables and have Request.Files pick it up at the destination url?

SOLUTION

In the end I solved it using the WebHelpers class here

Multipart forms from C# client

Community
  • 1
  • 1
Lee Englestone
  • 4,545
  • 13
  • 51
  • 85

3 Answers3

2

For anyone stumbling upon this question, the more modern method, using .NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet), is to use Microsoft.Net.Http. Here is an example:

private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(actionUrl, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}
Joshcodes
  • 8,513
  • 5
  • 40
  • 47
1

I use the following piece of code:

Usage

List<IPostDataField> Fields = new List<IPostDataField>();
Fields.Add(new PostDataField() { Name="nameOfTheField", Value="value" }); //simple field
Fields.Add(new PostDataFile() { Name="nameOfTheField", FileName="something.ext", Content = byte[], Type = "mimetype" });

string response = WebrequestManager.PostMultipartRequest(
    new PostDataEntities.PostData()
    {
        Fields = Fields
    }
    ,
            "url");

PostMultiPartRequest

    public static string PostMultipartRequest(PostData postData, string relativeUrl, IUserCredential userCredential)
    {
        string returnXmlString = "";

        try
        {
            //Initialisatie request
            WebRequest webRequest = HttpWebRequest.Create(string.Format(Settings.Default.Api_baseurl, relativeUrl));
            //Credentials
            NetworkCredential apiCredentials = userCredential.NetworkCredentials;
            webRequest.Credentials = apiCredentials;
            webRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(apiCredentials.UserName + ":" + apiCredentials.Password)));
            //Post!
            webRequest.Method = "POST";
            webRequest.ContentType = "multipart/form-data; boundary=";

            //Post
            //byte[] bytesToWrite = UTF8Encoding.UTF8.GetBytes(multipartData);
            string boundary = "";
            byte[] data = postData.Export(out boundary);
            webRequest.ContentType += boundary;
            webRequest.ContentLength = data.Length;
            using (Stream xmlStream = webRequest.GetRequestStream())
            {
                xmlStream.Write(data, 0, data.Length);
            }

            //webRequest.ContentType = "application/x-www-form-urlencoded";
            using (WebResponse response = webRequest.GetResponse())
            {
                // Display the status
                // requestStatus = ((HttpWebResponse)response).StatusDescription;

                //Plaats 'response' in stream
                using (Stream xmlResponseStream = response.GetResponseStream())
                {
                    //Gebruik streamreader om stream uit te lezen en om te zetten naar string
                    using (StreamReader reader = new StreamReader(xmlResponseStream))
                    {
                        returnXmlString = reader.ReadToEnd();
                    }
                }
            }
        }
        catch (WebException wexc)
        {
            switch (wexc.Status)
            {
                case WebExceptionStatus.Success:
                case WebExceptionStatus.ProtocolError:
                    log.Debug("bla", wexc);
                    break;
                default:
                    log.Warn("bla", wexc);
                    break;
            }
        }
        catch (Exception exc)
        {
            log.Error("bla");
        }

        return returnXmlString;

    }

IPostdataField

public interface IPostDataField
{
   byte[] Export();
}

PostDataField

public class PostDataField : IPostDataField
{
    public string Name { get; set; }
    public string Value { get; set; }

    #region IPostDataField Members

    public byte[] Export()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            StreamWriter sw = new StreamWriter(stream);
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", Name));
                sb.AppendLine();
                sb.AppendLine(Value);
                sw.Write(sb.ToString());
                sw.Flush();
            }

            stream.Position = 0;

            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int)buffer.Length);
            return buffer;
        }
    }

    #endregion
}

PostDataFile

public class PostDataFile : IPostDataField
{
    public Byte[] Content { get; set; }
    public string Name { get; set; }
    public string FileName { get; set; }
    public string Type { get; set; } // mime type

    public byte[] Export()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            StreamWriter sw = new StreamWriter(stream);

            StringBuilder sb = new StringBuilder();
            sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", Name, FileName));
            sb.AppendLine("Content-Type: " + Type);
            sb.AppendLine();

            sw.Write(sb.ToString());

            sw.Flush();

            stream.Write(Content, 0, Content.Length);

            stream.Position = 0;

            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int)buffer.Length);
            return buffer;
        }
    }
}

PostData

public class PostData
{
    public PostData() { Fields = new List<IPostDataField>(); }

    public List<IPostDataField> Fields { get; set; }

    public Byte[] Export(out string boundary)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            Random r = new Random();
            string tok = "";
            for (int i = 0; i < 14; i++)
                tok += r.Next(10).ToString();

            boundary = "---------------------------" + tok;
            using (StreamWriter sw = new StreamWriter(stream))
            {
                //sw.WriteLine(string.Format("Content-Type: multipart/form-data; boundary=" + boundary.Replace("--", "")));
                //sw.WriteLine();
                //sw.Flush();

                foreach (IPostDataField field in Fields)
                {
                    sw.WriteLine("--" + boundary);
                    sw.Flush();

                    stream.Write(field.Export(), 0, (int)field.Export().Length);
                }

                //1 keer om het af te leren
                //sw.WriteLine();
                sw.WriteLine("--" + boundary + "--");
                sw.Flush();

                stream.Position = 0;

                using (StreamReader sr = new StreamReader(stream))
                {
                    string bla = sr.ReadToEnd();

                    stream.Position = 0;
                    Byte[] toExport = new Byte[stream.Length];
                    stream.Read(toExport, 0, (int)stream.Length);
                    return toExport;
                }

            }
        }
    }
}
Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120
1

SOLUTION

In the end I solved it using the WebHelpers class here

Multipart forms from C# client

Works a treat.

-- Lee

Community
  • 1
  • 1
Lee Englestone
  • 4,545
  • 13
  • 51
  • 85