i have some troubles with uploading image onto a server
here's the code:
var uploadServer = api.Photo.GetUploadServer(123);
var c = new HttpClient();
var formData = new MultipartFormDataContent();
var requestContent = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(File.ReadAllBytes("images/amogus.jpg"));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "amogus.jpg"
};
formData.Add(fileContent);
var responseFile = Encoding.ASCII.GetString(await c.PostAsync(uploadServer.UploadUrl, formData));
in the first i'm getting a link to upload image there, then i'm adding image to formData and trying to send with PostAync, on this step i have trouble because PostAsync wants uploadUrl to be byte[] but it is a HttpResponseMessage. how do i convert it?
also here is error message:
Argument 1: cannot convert from 'System.Net.Http.HttpResponseMessage' to 'byte[]'
CodePudding user response:
You can use ReadAsStreamAsync
and then pass it to a StreamReader
to read the string.
You are also missing various using
blocks, and you can also stream your file directly into ByteArrayContent
. requestContent
appears to be unused here.
static HttpClient c = new HttpClient(); // always keeps static or you could get socket exhaustion
using (var formData = new MultipartFormDataContent())
using (var fileContent = new StreamContent(File.Open("images/amogus.jpg", FileMode.Open, FileAccess.Read)))
{
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "amogus.jpg"
};
formData.Add(fileContent);
using (var response = await c.PostAsync(uploadServer.UploadUrl, formData))
using (var responseStream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(responseStream, Encoding.ASCII))
{
var yourString = await responseStream.ReadToEndAsync();
// do stuff with string
}
}
Are you sure you want ASCII
and not UTF8
? If so you could shorten the whole thing to this
using (var formData = new MultipartFormDataContent())
using (var fileContent = new StreamContent(File.Open("images/amogus.jpg", FileMode.Open, FileAccess.Read)))
{
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "amogus.jpg"
};
formData.Add(fileContent);
using (var response = await c.PostAsync(uploadServer.UploadUrl, formData))
{
var yourString = await response.ReadAsStringAsync();
// do stuff with string
}
}