C# Загрузка файла запросом POST (multipart/form-data)

imrum

Client
Регистрация
24.03.2020
Сообщения
6
Благодарностей
2
Баллы
3
Интересует вопрос, как в точности повторить такой запрос
C#:
POST https://server.com HTTP/1.1
Content-Type: multipart/form-data; boundary=c6c302b53b6645cc88c35c9cdfb85c6e
Content-Length: 124148
Host: server.com
Connection: Keep-Alive
Accept-Encoding: gzip

--c6c302b53b6645cc88c35c9cdfb85c6e
Content-Disposition: form-data; name="id"; filename="user"
Content-Type: image/*
Content-Length: 123156
{фотка}
--c6c302b53b6645cc88c35c9cdfb85c6e
Content-Disposition: form-data; name="from_id"
Content-Length: 9

132869629
--c6c302b53b6645cc88c35c9cdfb85c6e--

Делать пытался так
C#:
string path = @"D:\001.jpg";
FileInfo strFileInfo = new FileInfo(path);
string fileName = strFileInfo.Name;
long fileLength = strFileInfo.Length;

int fromIdLength = fromId.Length;


string data = "--" + boundary;
data += Environment.NewLine + "Content-Disposition: form-data; name=\"id\"; filename=\"user\"";
data += Environment.NewLine + "Content-Type: image/*";
data += Environment.NewLine + $"Content-Length: {fileLength}";

data += Environment.NewLine + Environment.NewLine + path;
data += Environment.NewLine + "--" + boundary;
data += Environment.NewLine + "Content-Disposition: form-data; name=\"from_id\"";
data += Environment.NewLine + $"Content-Length: {fromIdLength}";
data += Environment.NewLine + Environment.NewLine + fromId;

data += Environment.NewLine    + "--" + boundary + "--" + Environment.NewLine;

string s = ZennoPoster.HTTP.Request(
    InterfacesLibrary.Enums.Http.HttpMethod.POST,
    url: "https://server.com/",
    content: data,
    contentPostingType: "multipart/form-data; boundary=" + boundary,
    Encoding: "UTF-8",
    respType: ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly,
    Timeout: 30000,
    UserAgent: userAgent,
    proxy: proxy
);
Но..
  • Если указывать filename="user" без расширения, Content-Type меняется на application/octet-stream. Параметр filename должен всегда быть равен user, как бы там файл не назывался.
  • Content-Length вообще пропадает из запроса.
  • Ну и еще меняется порядок, сначала секция с информацией о файле становится последней, а нужно чтобы была первой.
 

doc

Client
Регистрация
30.03.2012
Сообщения
8 684
Благодарностей
4 641
Баллы
113
порядок вряд ли важен. Из того, что бросилось в глаза, boundary не надо совать в contentPostingType в зенно. Оно там автоматом подтягивается
 

imrum

Client
Регистрация
24.03.2020
Сообщения
6
Благодарностей
2
Баллы
3
Да в том то и дело что важен. Загружать дает и так, но почти моментально прилетает бан.
 

imrum

Client
Регистрация
24.03.2020
Сообщения
6
Благодарностей
2
Баллы
3
Может кому пригодится
C#:
Image newImage = Image.FromFile(@"D:\img.jpg");
ImageConverter _imageConverter = new ImageConverter();
byte[] paramFileStream = (byte[])_imageConverter.ConvertTo(newImage, typeof(byte[]));



using (var client = new HttpClient())
{
    var streamImg = new StreamContent(new MemoryStream(paramFileStream));
    streamImg.Headers.Add("Content-Disposition", "form-data; name=\"image\"; filename=\"photo\"");
    streamImg.Headers.Add("Content-Type", "image/*");
    streamImg.Headers.Add("Content-Length", paramFileStream.Length.ToString());
   
    string param_1 = "xxxxxxxxxxx";
    var streamVal_1 = new StringContent(param_1);
    streamVal_1.Headers.Add("Content-Disposition", "form-data; name=\"from_id\"");
    streamVal_1.Headers.Add("Content-Length", param_1.Length.ToString());
    streamVal_1.Headers.Remove("Content-Type");
   
    var formContent = new MultipartFormDataContent
    {
        {streamImg,"id","user"},
        {streamVal_1, param_1},
    };
   
    var response = client.PostAsync("https://server.com", formContent).Result;

    if (response.IsSuccessStatusCode)
    {
        var responseContent = response.Content;
        string responseString = responseContent.ReadAsStringAsync().Result;
    }
}
 
Последнее редактирование:
  • Спасибо
Реакции: bizzon и eee

Кто просматривает тему: (Всего: 1, Пользователи: 0, Гости: 1)