0

I have today a program that I can post through to my site, but I need to add file upload support to my program (for jpg). I had such a problem just getting my program to post, and now after many hours I can't get it to work with file upload.

Today my code is not very good but it works and I'm the only one using it. Here is my code, abit stripped but I hope you get the idea what I need help with. Thanks!

("upfile" is the input field name for images)

public static string Post(string url, int id, string message)
{
    try
    {
        string param =
            string.Format(
                "MAX_FILE_SIZE=2097152&id={0}&com={1}&upfile", id, message);

        byte[] bytes = Encoding.ASCII.GetBytes(param);

        var post = (HttpWebRequest)WebRequest.Create(url);

        post.ProtocolVersion = HttpVersion.Version10;
        post.Method = "POST";
        post.AllowAutoRedirect = false;
        post.ContentType = "application/x-www-form-urlencoded";
        post.ContentLength = bytes.Length;

        post.UserAgent =
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.15) Gecko/2009101601 Firefox/3.0.15 (.NET CLR 3.5.30729)";
        post.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

        Stream requestStream = post.GetRequestStream();
        requestStream.Write(bytes, 0, bytes.Length);
        requestStream.Close();

        var webResponse = (HttpWebResponse)post.GetResponse();
        var sr = new StreamReader(webResponse.GetResponseStream());
        return sr.ReadToEnd();
    }
    catch (Exception exception)
    {
        return null;
    }
}

Edit: Sorry for my poor explanation here is what I need help with: I use the method above today to post on my site, but I need add support to upload files in my method. I can't change how the webpage works in the close future so it have to be done by using a POST request. I can't get it to work then I try to do it myself, so I'm wondering if anybody could help me with what need to be added to read a image and post it with the request!

Thanks!

3 Answers3

1

You need to use the encoding of multipart/form-data instead of application/x-www-form-urlencoded, and then you need to encode the post data accordingly

See Upload files with HTTPWebrequest (multipart/form-data)

Community
  • 1
  • 1
Martin Ernst
  • 5,629
  • 2
  • 17
  • 14
0

I'm assuming you need a better solution than your current one. If you are on c#, there is a FILE upload control that you can use to upload files. You can even restrict it to the types of valid files that you allow.

Control is FileUpload

edocetirwi
  • 542
  • 5
  • 22
0

Shouldnt your Content type be multipart/form-data; ? If it is possible for you to use a upload class I can make one available to you.

Ademar
  • 5,657
  • 1
  • 17
  • 23