For upload an image or file to a remote server, you should convert the file to byte, you can find how to do it in here.
We need to put the image to the MultipartFormDataContent and send to server for upload, so need to create the MultipartFormDataContent object first:
MultipartFormDataContent content = new MultipartFormDataContent(); ByteArrayContent baContent = new ByteArrayContent(logo); //the logo is the byte[] object from an image or file StringContent id = new StringContent("id"); //this is another paramter you need to pass to server baContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpg"); //set the media type is an image baContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = companyId + "_logo.jpg", // save the file name into server side Name = "file", }; content.Add(baContent, "file"); content.Add(id, companyId.ToString());
After that we need to pass the content via the server API:
Do you want to be a good trading in cTrader? >> TRY IT! <<
var response = await client.PostAsync("http://www.yourserver.com/upload", content); var result = response.Content.ReadAsStringAsync().Result; if (result == null || result.ToString() != "\"OK\"") { return false; }
I just show you the keycodes, of course, you should do some error handling for this case, something like the try…catch…, and below is the full function for this upload case:
public static async Task<bool> UploadCompanyLogo(int companyId, byte[] logo) { try { MultipartFormDataContent content = new MultipartFormDataContent(); ByteArrayContent baContent = new ByteArrayContent(logo); //the logo is the byte[] object from an image or file StringContent id = new StringContent("id"); //this is another paramter you need to pass to server baContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpg"); //set the media type is an image baContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = companyId + "_logo.jpg", // save the file name into server side Name = "file", }; content.Add(baContent, "file"); content.Add(id, companyId.ToString()); var response = await client.PostAsync("http://www.yourserver.com/upload", content); var result = response.Content.ReadAsStringAsync().Result; if (result == null || result.ToString() != "\"OK\"") { return false; } } catch(Execption ex) { //do something to write the error logs.... return false; } return true; }
Views: 41
Total Views: 865 ,