Currently im working on a xamarin forms app, that upload image to Strapi API. To take a picture from the camera i'm using CrossMedia Plugin
var photo = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions() { PhotoSize= PhotoSize.Small, CompressionQuality = 100 });
if (photo != null)
ProductPic.Source = ImageSource.FromStream(() => { return photo.GetStream(); });
than send the photo in post Method :
HttpClient httpClient = new HttpClient();
MultipartFormDataContent mt = new MultipartFormDataContent();
photo.GetStream().Position = 0;
StreamContent imagePart = new StreamContent(photo.GetStream());
imagePart.Headers.Add("files", "jpg");
mt.Add(imagePart, string.Format("image"), string.Format("bsk.jpeg"));
var response = await httpClient.PostAsync("http://111.111.111.111:2222/upload", mt);
The problem that im facing this error
"{\"statusCode\":400,\"error\":\"Bad Request\",\"message\":\"Bad Request\",\"data\":{\"errors\":[{\"id\":\"Upload.status.empty\",\"message\":\"Files are empty\"}]}}
The error points the image part is empty , try to replace StreamContent with ByteArrayContent , send ByteArray instead of Stream .
HttpClient httpClient = new HttpClient();
MultipartFormDataContent mt = new MultipartFormDataContent();
mt.Headers.ContentType.MediaType = "multipart/form-data";
var upfilebytes = File.ReadAllBytes(photo.Path);
mt.Add(new ByteArrayContent(upfilebytes, 0, upfilebytes.Count()), string.Format("image"), string.Format("bsk.jpeg"));
var response = await httpClient.PostAsync("http://111.111.111.111:2222/upload", mt);
Refer to
https://stackoverflow.com/a/61095848/8187800.
Related
I am using AWS SDK to upload a file to S3. Locally works fine, but on the deployed server it gives this error: Received an unexpected EOF or 0 bytes from the transport stream.
Here is the code:
var location = $"some-location";
using (var stream = request.File.OpenReadStream())
{
var putRequest = new PutObjectRequest
{
Key = location,
BucketName = configuration["AWS:BucketName"],
InputStream = stream,
AutoCloseStream = true,
ContentType = request.File.ContentType
};
var putResponse = await amazonS3.PutObjectAsync(putRequest);
response.IsValid = putResponse.HttpStatusCode == System.Net.HttpStatusCode.OK;
}
request.File is FormFile and passed in from controller like this:
public async Task<UploadResponse> Upload(IFormFile formFile)
{
if (formFile is null || formFile.Length <= 0)
{
throw new ArgumentNullException(nameof(formFile));
}
//TODO: Validate File Extension
UploadResponse response;
UploadCommand command = new UploadCommand();
command.File = formFile;
response = await mediator.Send(command);
return response;
}
I am working on a project that has a file .gitlab-ci.yml in master branch. I am trying to update that .yml file using gitlab api (https://docs.gitlab.com/ee/api/commits.html#create-a-commit-with-multiple-files-and-actions) but using it from a asp.net core 5 application.
Here is my try. But I am getting 400 bad request error. Kindly help to find out what is wrong I am doing here.
public IActionResult Update()
{
var url = $"{ProjectUrl}/{ProjectId}/repository/commits/";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "PUT";
httpRequest.Headers["PRIVATE-TOKEN"] = ClientSecret;
httpRequest.ContentType = "application/json";
var str =
#"{'branch': 'master',
'commit_message': 'some commit message',
'actions': [
{
'action': 'update',
'file_path': '.gitlab-ci.yml',
'content': 'some content'
}
}";
var data = str;
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(data);
}
var httpResponse = (HttpWebResponse)httpRequest.GetResponse(); // I'm getting 400 Bad request error here
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
// rest of the code goes here
}
return View();
}
Well after rewriting the code, finally I am able to make it works. Posting my solution here in a hope that someone will be benefited from this. Cheers!
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("PUT"), "https://ProjectUrl/api/v4/projects/projectid/repository/%2Egitlab%2Dci.yml"))
{
request.Headers.TryAddWithoutValidation("PRIVATE-TOKEN", "<your_private_token>");
request.Content = new StringContent("{\"branch\": \"master\", \"author_email\": \"user#email.com\", \"author_name\": \"user\", \n \"content\": \"some content\", \"commit_message\": \"update file\"}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var response = await httpClient.SendAsync(request);
}
}
I am using Dropbox api uploadAsync to upload an image which in itself is passed in raw data form from another POST request. The upload is successful in terms that there is a file now on dropbox. But when I access that file, it says it has no contents. Why is it uploading file without content? Here is what I have tried
MemoryStream memoryStream = new MemoryStream();
imageStream.Position = 0;
memoryStream.Position = 0;
imageStream.CopyTo(memoryStream);
var task = Task.Factory.StartNew(() => {
var dropboxClient = new DropboxClient(token);
var folder = "XYZ";
var fileName = "ABC";
var upload = dropboxClient.Files.UploadAsync(folder + "/" + fileName, Dropbox.Api.Files.WriteMode.Add.Instance, autorename:true, body: memoryStream);
upload.Wait();
});
task.Wait();
imageStream is the Stream which I get from a POST request. It has raw image data.
Any help would be appreciated
For authentication I am using Auth0 AuthenticationApi. In Account Controller, I need to fetch the user_metadata but it's missing. Any alternative to fetch the user_metadata?
AuthenticationApiClient client = new AuthenticationApiClient(new Uri($"https://{_auth0Options.Domain}/"));
var authenticateResponse = await client.GetTokenAsync(new ResourceOwnerTokenRequest
{
ClientId = _auth0Options.ClientId,
ClientSecret = _auth0Options.ClientSecret,
Scope = "openid",
Realm = _auth0Options.Connection,
Username = vm.EmailAddress,
Password = vm.Password
});
var user = await client.GetUserInfoAsync(authenticateResponse.AccessToken);
if (user.UserMetadata != null)
{
// Giving error...any alternative to access the userMetaData ?
}
Yes, as far as I see it now, the legacy call still works. However, I don't have a non-legacy solution yet :(
using (var client = GetClient())
{
var jObject = new JObject(new JProperty("id_token", id_token));
var response = await client.PostAsJsonAsync("tokeninfo", jObject);
if (response.IsSuccessStatusCode)
{
var userProfileJson = JObject.Parse(await response.Content.ReadAsStringAsync());
retVal.user_id = userProfileJson.Value<string>("user_id");
retVal.email = userProfileJson.Value<string>("email");
retVal.user_name = userProfileJson.Value<string>("nickname");
if (userProfileJson.Value<string>("created_at") != null)
{
retVal.created_at = userProfileJson.Value<DateTime>("created_at");
}
var exists = userProfileJson.TryGetValue("user_metadata", out JToken meta);
I've tried with only simple text but i want to sent email with attachment.
var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("Test","test#gmail.com"));
emailMessage.To.Add(new MailboxAddress("Demo", "demo#gmail.com"));
emailMessage.Subject = "Hello";
emailMessage.Body = new TextPart("html") { Text = "Hi............" };
//I want Attachment here with body text..
//Send Email.
using (var client = new SmtpClient())
{
await client.ConnectAsync("smtp.gmail.com", 587, false);
client.AuthenticationMechanisms.Remove("XOAUTH2");
await client.AuthenticateAsync("uid", "pass");
await client.SendAsync(emailMessage);
await client.DisconnectAsync(true);
}
var multipart = new Multipart("mixed");
multipart.Add(new TextPart("html") { Text = "your body message"});
// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
ContentObject = new ContentObject (File.OpenRead (path), ContentEncoding.Default),
ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName (path)
};
multipart.Add(attachment);
emailMessage.Body = multipart;
For more detail, Please visit here