0

我想效仿这个请求

这是来自嗅探器的日志

 -----------------------------708299735697
Content-Disposition: form-data; name="_file"

1.jpg
-----------------------------708299735697
Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: image/png

‰PNG
............

那是我在 csharp 上的代码。

var taimalda = DateTime.Now.Ticks;  
var boundary = "------------------------" + taimalda ;
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 + "Content-Type: image/png";

var req = (HttpWebRequest)HttpWebRequest.Create("http://xxx.ru/new_style/flash_uploader/upload.php?fileapi"+taimalda);
req.CookieContainer = s; // 
System.Net.ServicePointManager.Expect100Continue = false;
req.Referer = "http://www.xxx.ru/user/setting/set_info"; // add referer

req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0";   // add useragent
req.Method = WebRequestMethods.Http.Post;  // post request
req.ContentType = "multipart/form-data; boundary=" + boundary;

using (var reqStream = req.GetRequestStream())
{
    var reqWriter = new StreamWriter(reqStream);
    var tmp = string.Format(propFormat, "_file", "1.jpg");
    reqWriter.Write(tmp);
    tmp = string.Format(fileHeaderFormat, "file", "blob");
    reqWriter.Write(tmp);
    reqWriter.Flush();
}
var res = req.GetResponse();
using (var resStream = res.GetResponseStream())
{
     var reader = new StreamReader(resStream);
     var ext = reader.ReadToEnd();
}

但是这段代码只发送了没有我的文件的标题(1.jpg)

    -----------------635031060420469298
    内容处置:表单数据;名称="_file"

    1.jpg
    --------------------------635031060420469298
    内容处置:表单数据;名称=“文件”;文件名=“blob”
    内容类型:图片/png
4

3 回答 3

0

您需要将文件字节写入Stream,而不是StreamWriter

using (var reqStream = req.GetRequestStream())
using (var reqWriter = new StreamWriter(reqStream))
{
    reqWriter.Write(propFormat, "_file", "1.jpg");
    reqWriter.Write(fileHeaderFormat, "file", "blob");

    int ken = fs.Read(buffer, 0, buffer.Length);
    reqStream.Write(buffer, 0, ken);
    reqStream.Flush();
}
于 2013-05-02T18:43:42.880 回答
0

我看不到您实际读取 1.jpg 文件的字节并将其写入请求流的任何地方。

于 2013-05-02T17:49:07.200 回答
0

也许我的代码会帮助你

var client = new HttpClient();
                client.BaseAddress = new Uri(BASE_URL);
                var multipart = new MultipartFormDataContent();

                foreach(var file in files)
                {
                    var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(file.FullName));
                    multipart.Add(fileContent, "files", file.Name);
                }


                return client.PostAsync("Images", multipart);

迟到总比不到好

于 2018-11-16T10:34:04.603 回答