Uploading files with HTTP PUT

  • Автор темы Автор темы tsuna123
  • Дата начала Дата начала

tsuna123

Новичок
Регистрация
29.10.2018
Сообщения
11
Реакции
0
Баллы
1
How do i use HTTP PUT to upload files?

Im using C# code to send the request

Код:
Развернуть Свернуть Копировать
var response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.PUT,
"link",
"",
"application/x-www-form-urlencoded",
instance.GetProxy(),
"",
ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.HeaderAndBody,
AdditionalHeaders: new []{"Authorization:Bearer " + oauth" }
);

return response;

how do i upload files with this?
or is there a better alternative?

Thanks in advance
 
It's the same as POST with multipart:
var response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.PUT,
"https://httpbin.org/put",
@"-----------------------------77748066757751
Content-Disposition: form-data; name=""file""; filename=""cat.jpg""
Content-Type: image/jpeg

C:\Downloads\multipart\cat.jpg
-----------------------------77748066757751--",
"multipart/form-data",
"",
"",
ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly
);
return response;
 
  • Спасибо
Реакции: tsuna123
It's the same as POST with multipart:
Код:
Развернуть Свернуть Копировать
var response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.PUT,
project.Variables["url_upload"].Value,
@"-----------------------------77748066757751
Content-Disposition: form-data; name=""file""; filename=""123.rar""
Content-Type: application/x-rar-compressed

C:\папка\папка\123.rar
-----------------------------77748066757751--",
"multipart/form-data",
"",
"",
ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly
);
return response;

Использую данный код, в яндекс диск rest api, rar создаётся, но не закачивается.
При скачивании битый архив. В чём может быть проблема? С txt та же беда, создаётся новый файл с текстом директории (C:\папка\папка\123.txt).
Хотя в файле 123.txt - лежит другой текст

Код:
Развернуть Свернуть Копировать
PUT /a/otpusk.avi HTTP/1.1
Host: webdav.yandex.ru
Accept: */*
Authorization: OAuth 0c4181a7c2cf4521964a72ff57a34a07
Etag: 1bc29b36f623ba82aaf6724fd3b16718
Sha256: T8A8H6B407D7809569CA9ABCB0082E4F8D5651E46D3CDB762D02D0BF37C9E592
Expect: 100-continue
Content-Type: application/binary
Content-Length: 103134024

<содержимое файла>
 
Последнее редактирование:
It's the same as POST with multipart:
Thanks for the help but i dont think its working for me...

When i check the request traffic, this is what the request body looks like when i do it on the website
4ec39588fd9ece615087deb178ba51b5.png

This is what the request body looks like when i try it with the code
022229a9246af0a05e31d4e88d84aef0.png

Doesnt look like the file is being chosen properly?

Also,

@"-----------------------------77748066757751
-----------------------------77748066757751--",

What do these parts mean?
 
Thanks for the help but i dont think its working for me...

When i check the request traffic, this is what the request body looks like when i do it on the website
4ec39588fd9ece615087deb178ba51b5.png

This is what the request body looks like when i try it with the code
022229a9246af0a05e31d4e88d84aef0.png

Doesnt look like the file is being chosen properly?

Also,

@"-----------------------------77748066757751
-----------------------------77748066757751--",

What do these parts mean?
How do you encode a file in your request? In bytes?
 
How do you encode a file in your request? In bytes?

can you show me how i can take a image link convert to Bytes and upload it using the PUT request like the one u showed above ?

string Url = "https://image_link";
using (var webClient = new System.Net.WebClient()) {
byte[] imageBytes = webClient.DownloadData(Url);

}

var response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.PUT,
"https://httpbin.org/put",
imageBytes[0],
"multipart/form-data",
"",
"",
ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly
);
return response;

im trying this but its not working, i already imported all references/dll needed for webclient, only issue is HTTP PUT
 
H
can you show me how i can take a image link convert to Bytes and upload it using the PUT request like the one u showed above ?



im trying this but its not working, i already imported all references/dll needed for webclient, only issue is HTTP PUT
Here are examples on how to convert image to bytes - https://stackoverflow.com/questions/3801275/how-to-convert-image-to-byte-array
You may convert image like this instead of webclient:
Код:
Развернуть Свернуть Копировать
byte[] mageBytes  = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path));
 
H

Here are examples on how to convert image to bytes - https://stackoverflow.com/questions/3801275/how-to-convert-image-to-byte-array
You may convert image like this instead of webclient:
Код:
Развернуть Свернуть Копировать
byte[] mageBytes  = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path));

hi thanks, i already have converted the image into bytes but im not sure how to add it into the PUT request
 
@VladZen please help me with this last part ive been trying for a while but no luck
 
hi thanks, i already have converted the image into bytes but im not sure how to add it into the PUT request
I don't quite understand what problem you have...
This code converts the image to bytes automatically. all you need is just insert link to image at the beginning.
And put the link to website where to upload image in var response string.
Код:
Развернуть Свернуть Копировать
string Url = "https://image_link";
using (var webClient = new System.Net.WebClient()) {
byte[] imageBytes = webClient.DownloadData(Url);

}

var response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.PUT,
"https://httpbin.org/put",
imageBytes[0],
"multipart/form-data",
"",
"",
ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly
);
return response;
 
I don't quite understand what problem you have...
This code converts the image to bytes automatically. all you need is just insert link to image at the beginning.
And put the link to website where to upload image in var response string.
Код:
Развернуть Свернуть Копировать
string Url = "https://image_link";
using (var webClient = new System.Net.WebClient()) {
byte[] imageBytes = webClient.DownloadData(Url);

}

var response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.PUT,
"https://httpbin.org/put",
imageBytes[0],
"multipart/form-data",
"",
"",
ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly
);
return response;


i tried running that code but is is not runable,
this is what is says in the log "
Compile code of Error in action "CS0103" "The name 'imageBytes' does not exist in the current context". [Row: 9; Column: 1]
"

Код:
Развернуть Свернуть Копировать
byte[] imageBytes;
string Url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
using (var webClient = new System.Net.WebClient()) {
imageBytes = webClient.DownloadData(Url);
}

var response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.PUT,
"https://httpbin.org/put",
imageBytes[0],
"multipart/form-data",
"",
"",
ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly
);
return response;

So i declared imageBytes outside but i am still geting error message:

Compile code of Error in action "CS1502" "The best overloaded method match for 'ZennoLab.CommandCenter.ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod, string, string, string, string, string, ZennoLab.InterfacesLibrary.Enums.Http.ResponceType, int, string, string, bool, int, string[], string, bool, bool, ZennoLab.InterfacesLibrary.ProjectModel.ICookieContainer)' has some invalid arguments". [Row: 7; Column: 16]

Compile code of Error in action "CS1503" "Argument 3: cannot convert from 'byte' to 'string'". [Row: 9; Column: 1]
 
i tried running that code but is is not runable,
this is what is says in the log "
Compile code of Error in action "CS0103" "The name 'imageBytes' does not exist in the current context". [Row: 9; Column: 1]
"

Код:
Развернуть Свернуть Копировать
byte[] imageBytes;
string Url = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
using (var webClient = new System.Net.WebClient()) {
imageBytes = webClient.DownloadData(Url);
}

var response = ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod.PUT,
"https://httpbin.org/put",
imageBytes[0],
"multipart/form-data",
"",
"",
ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.BodyOnly
);
return response;

So i declared imageBytes outside but i am still geting error message:

Compile code of Error in action "CS1502" "The best overloaded method match for 'ZennoLab.CommandCenter.ZennoPoster.HTTP.Request(ZennoLab.InterfacesLibrary.Enums.Http.HttpMethod, string, string, string, string, string, ZennoLab.InterfacesLibrary.Enums.Http.ResponceType, int, string, string, bool, int, string[], string, bool, bool, ZennoLab.InterfacesLibrary.ProjectModel.ICookieContainer)' has some invalid arguments". [Row: 7; Column: 16]

Compile code of Error in action "CS1503" "Argument 3: cannot convert from 'byte' to 'string'". [Row: 9; Column: 1]
Something wrong with arguments in this method... - https://help.zennolab.com/en/v5/zennoposter/5.27.0.0/topic758.html
 
Использую данный код, в яндекс диск rest api, rar создаётся, но не закачивается.
назрела аналогичная проблема. Удалось как-то ее победить? Нейронку выдрочил, но она также не может родить рабочего решения, даже на коде.
Upd: решение найдено...

Если что, то получилось решить задачу по загрузке файла на я.диск по апи только через curl:


C#:
Развернуть Свернуть Копировать
// Параметры
string filePath = project.Directory + @"\file\" + project.Variables["temp"].Value;
string uploadUrl = project.Json.href.ToString(); // полученный get-запросом url для загрузки файла

// Формируем команду curl с выводом заголовков
string curlCmd = $"curl -i -T \"{filePath}\" \"{uploadUrl}\"";

// Запуск процесса
var proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = "/C " + curlCmd;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();

string output = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();

// Формируем полный ответ
string fullResponse = "=== STDOUT ===\n" + output + "\n\n=== STDERR ===\n" + error;

// Логирование результата
project.SendInfoToLog("Ответ curl:", true);
project.SendInfoToLog(fullResponse, true);

// Сохраняем полный ответ в переменную
project.Variables["api_response"].Value = fullResponse;

// Проверка результата
if (proc.ExitCode == 0)
{
    project.SendInfoToLog("✓ Файл отчета загружен через curl!", true);
    
    // Извлекаем код ответа из заголовков
    if (output.Contains("HTTP/1.1 201 Created"))
    {
        project.SendInfoToLog("Код ответа: 201 Created", true);
        
        // Извлекаем Location из заголовков
        string[] lines = output.Split('\n');
        foreach (string line in lines)
        {
            if (line.StartsWith("Location:"))
            {
                string location = line.Substring(9).Trim();
                project.SendInfoToLog("Файл сохранен по пути: " + Uri.UnescapeDataString(location), true);
                break;
            }
        }
    }
}
else
{
    project.SendInfoToLog("ОШИБКА загрузки через curl! Код: " + proc.ExitCode, true);
}
 
Последнее редактирование:
  • Спасибо
Реакции: bigcajones

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