Using HttpWebRequest to POST data/upload image using multipart/form-data

前端 未结 3 716
情歌与酒
情歌与酒 2020-12-03 03:20

I am trying to use the ImageShack API to upload images. To use it, I am supposed to POST the image using multipart/form-data. I did it like ...

3条回答
  •  一向
    一向 (楼主)
    2020-12-03 04:09

    I finally got it with the following code ...

    var boundary = "------------------------" + DateTime.Now.Ticks;
    var newLine = Environment.NewLine;
    var propFormat = "--" + boundary + newLine +
                        "Content-Disposition: form-data; name=\"{0}\"" + newLine + newLine + 
                        "{1}" + newLine;
    var fileHeaderFormat = "--" + boundary + newLine +
                            "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + newLine;
    
    var req = (HttpWebRequest)HttpWebRequest.Create("http://jm/php/upload.php");
    req.Method = WebRequestMethods.Http.Post;
    req.ContentType = "multipart/form-data; boundary=" + boundary;
    
    using (var reqStream = req.GetRequestStream()) {
        var reqWriter = new StreamWriter(reqStream);
        var tmp = string.Format(propFormat, "str1", "hello world");
        reqWriter.Write(tmp);
        tmp = string.Format(propFormat, "str2", "hello world 2");
        reqWriter.Write(tmp);
        reqWriter.Write("--" + boundary + "--");
        reqWriter.Flush();
    }
    var res = req.GetResponse();
    using (var resStream = res.GetResponseStream()) {
        var reader = new StreamReader(resStream);
        txt1.Text = reader.ReadToEnd();
    }
    

    Notice boundaries have to begin with -- {boundary declared in ContentType} and ending boundary must begin & end with -- . in my case, I originally used

    var propFormat = boundary + newLine +
                        "Content-Disposition: form-data; name=\"{0}\"" + newLine + newLine + 
                        "{1}" + newLine;
    

    replace it with

    var propFormat = "--" + boundary + newLine +
                        "Content-Disposition: form-data; name=\"{0}\"" + newLine + newLine + 
                        "{1}" + newLine;
    

    and everything works

提交回复
热议问题