Image not uploaded in Xamarin via API - xamarin

I have a problem that is still unclear: I am trying to upload an image from Xamarin via the API. I check the code for the OK message, but the image can't be uploaded to the Server, I tried to test the API on Postman, swagger, it works fine. I checked read_external_storage and write_external_storage
async void pickimg_Tapped(System.Object sender, EventArgs e)
{
var pickResult = await MediaPicker.PickPhotoAsync();
var content = new MultipartFormDataContent();
content.Add(new StreamContent(await pickResult.OpenReadAsync()), "file", pickResult.FileName);
var httpClient = new HttpClient();
var responses = await httpClient.PostAsync("https://api.com/api/UploadFileFeeds", content);
lb_status.Text = responses.StatusCode.ToString();
}
I check the responses value returns OK. However I can't find the image on the Server's folder. Note that when I test on Postman vs swagger, the image is saved on the Server. What did I do wrong? Ask for a solution from everyone

Related

Connect Xamarin to DB

I'm starting learning Xamarin and i face problem in connecting app with DB. i built rest web services with method get and i uplode it in host. after that i add this code in app
private async Task<List<testClass>> GetlistAsync()
{
var uri = new Uri(string.Format("my web service link", string.Empty));
var response = await httpClient.GetAsync(uri);
List<testClass> Items = new List<testClass>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Items = JsonConvert.DeserializeObject<List<testClass>>(content);
}
return Items;
}
the problem is whenever i add run. the code will stop after httpclint. getasync line without doing lines after it
pleas help as fast as possible
thanks

How to let user click to open the CSV file in browser C# BotFramework SDK3

As the title, I want to let user click to open a file in browser which is created by Bot. I'm using webChat.
The code is what I have tried.
In botframework-emulator, if I click the link, the CSV file will open in the browser.
But in the webChat, it will request user to download, not open in the browser.
var aaa = await GetCSVAttachmentAsync(replymes.ServiceUrl, replymes.Conversation.Id);
foreach(var aa in aaa)
replymes.Attachments.Add(aa);
await context.PostAsync(replymes);
private async Task<IList<Attachment>> GetCSVAttachmentAsync(string serviceUrl, string conversationId)
{
string str = "this is a text CSV";
byte[] array = Encoding.GetEncoding("shift_jis").GetBytes(str);
using (var connector = new ConnectorClient(new Uri(serviceUrl)))
{
var attachments = new Attachments(connector);
var response = await attachments.Client.Conversations.UploadAttachmentAsync(
conversationId,
new AttachmentData
{
Name = "userinfo.csv",
OriginalBase64 = array,
Type = "text/csv"
});
message.Add(new Attachment
{
Name = "userinfo.html",
ContentType = "text/html",
ContentUrl = response.Id
});
return message;
}
}
To solve this problem, I also tried storageV2. But it seems the URI can't be accessed directly.
I still couldn't figure it out without creating a real file.
But instead of using storage V2, I can solve the problem. The thought is as below.
Let the bot create a file.
Upload it to Storage V2 using static website
Send the static website to user.

Upload photos to Google Photos API - Error 500

I'm getting the error below while trying to upload media to Google Photos API, following the docs
This is how i retrieve my bytes array:
And this is how i make the request:
I've tried a lot of things and none of it work...
Note: I'm consuming other Google Photos API endpoints, such as Get Albums, Create Albums, Get Media and everything work as expected. The upload media is the only one i'm having trouble with.
Note 2: The token is being sent correctly.
Note 3: All the origin endpoints were configured in the google console (localhost included) so much so that other endpoints are working correctly.
Anyone can give me a light?
I am writing something similar in C# and was able to work with the photo api. My best advice is to double check headers. I hope this helps, additionally I added a postman screenshot of a successful call to the api:
public async Task<GoogleApiResponse> UploadPhoto(StorageFile photo)
{
var userInfo = UserInfoVault.GetUserInfo();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userInfo.AccessToken);
client.DefaultRequestHeaders.Add("X-Goog-Upload-File-Name", photo.DisplayName);
var fileStream = await photo.OpenAsync(FileAccessMode.Read);
var reader = new DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
byte[] pixels = new byte[fileStream.Size];
reader.ReadBytes(pixels);
var httpContent = new ByteArrayContent(pixels);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
HttpResponseMessage photoResponse = client.PostAsync(ApiEdnpoints.UploadPhoto, httpContent).Result;
string strResponse = await photoResponse.Content.ReadAsStringAsync();
return null;
}
Postman screenshot of successful call to upload a photo

Downloading a file from Azure Storage to client using Angular2 with .NET Web Api 2

I am trying to download a 1GB file from blob storage into the client. I used before Memory Stream and I get OutOfMemory exception.
now I am trying to open a read stream from the blob and send it directly to the client.
[HttpGet]
[ResponseType(typeof(HttpResponseMessage))]
public async Task<HttpResponseMessage> DownloadAsync(string file)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = await blob.OpenReadAsync("container", file);
result.Content = new StreamContent(stream);
return result;
}
The file is downloaded correctly, but the problem is: The code download the complete stream in the client, then the client sees the downloaded file.
I wanted the client to see the file as being downloaded, so the user knows that he is downloading something. Not just blocking the request and wait till it finished.
I am using FileSaver in Angular2:
this.controller.download('data.zip').subscribe(
data => {
FileSaver.saveAs(data, 'data.zip');
});
Has anybody an idea how to fix it?
Thank you!
To fix it you'd need to use the following javascript code instead:
var fileUri = "http://localhost:56676/api/blobfile"; //replace with your web api endpoint
var link = document.createElement('a');
document.body.appendChild(link);
link.href = fileUri;
link.click();
And then in your backend, make it like so:
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = await blob.OpenReadAsync("container", file);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "data.zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
I had the same problem.
The Solution I sorted out was -
First thing, the expected behaviour can occur only when client tries to download the file from blob and usually I prefer downloading the file from the client itself.
As in your case, try to get file blob uri and do some operations as below to open file in browser using Angular Router or simply window.location.href.
window.location.href = “https://*/filename.xlsx”
This worked for me.

image upload to server in windows phone8 app

I want to upload an image from the gallery or live pic (camera capture task) with some params; x = "some string", y = "some string", z = "some integer" and uploadimage = name of file tag in form.
Can anyone please help me?
Uploading image for WP8 was pain to setup. Many of the examples I follow was outdated and this took me days to research and finally got one to work. There are a few ways to upload:
1) Convert the image to a string and then you can send the image converted string via HTTP request. I've used this approach for Android, but haven't tried it for WP.
2) Upload the image via FTP and the text data via HTTP.
You have 3 choices to upload any File to server.
Convert file into Stream - recommend way
Convert file into ByteArray
Convert file into String
After that you can use HttpClient package make a POST request to server. Here is the code to demonstrate FileUpload by converting it into Stream.
Code:
public async void methodToUploadFile()
{
StorageFile file = await StorageFile.GetFileFromPathAsync("Assets/MyImage.png");
// var fileBytes = await GetBytesAsync(file);
HttpClient client = new HttpClient();
// give the server URI here
Uri requestUri = new Uri("Full Server URI", UriKind.Absolute);
MultipartFormDataContent formdata = new MultipartFormDataContent();
formdata.Add(new StringContent("some string"), "x");
formdata.Add(new StringContent("some string"), "y");
formdata.Add(new StringContent("some integer"), "z");
formdata.Add(new StreamContent(await file.OpenStreamForReadAsync()), "file", "MyImage.png");
// formdata.Add(new ByteArrayContent(fileBytes), "file", "MyImage.png");
// Make a POST request here
var res = await client.PostAsync(requestUri, formdata);
}
Hope this helps..!

Resources