'How to Convert Base64 to Char Array - C# - Microsoft Graph?
My code receives a Base64 value as a String (Public String Base64Foto). I must take this value and convert it to Char[] to send it to graph Microsoft.
private static async Task<bool> EnviarMicrosoft(DadosApData dadosApData)
{
try
{
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenantID";
var clientId = "clientID";
var clientSecret = "clientSecret";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var bytes = Convert.FromBase64String(dadosApData.Base64Foto);
var charFromByte = System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();
using var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(charFromByte));
await graphClient.Users[dadosApData.Email].Photo.Content.Request().PutAsync(stream);
return true;
}
catch (Exception ex)
{
LambdaLogger.Log(ex.Message);
throw ex;
}
}
When I do this in Postman, it works normally (as a binary), but when I try to pass this to the code, it doesn't work, is my conversion wrong?
PS: I'm Receving the error: Microsoft.Fast.Profile.Core.Exception.ImageNotFoundException
Solution 1:[1]
This is my code and it can update the user photo:
Controller:
[HttpPost]
public async Task UploadAsync(IFormFile file) {
var ms = new MemoryStream();
file.CopyTo(ms);
var fileBytes = ms.ToArray();
//string s = Convert.ToBase64String(fileBytes);
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "hanxia.onmicrosoft.com";
var clientId = "client_id";
var clientSecret = "client_secret";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var res = await graphClient.Users["user_id"].Photo.Content.Request().PutAsync(new MemoryStream(fileBytes, 0, fileBytes.Length));
}
cshtml:
<input id="picContent" type="file" name="photo" value="please upload a picture" />
<input id="btn1" type="button" value="upload"/>
@section scripts
{
<script>
$("#btn1").click(function(){
var formData = new FormData();
var img = $("#picContent")[0].files[0];
console.log(img);
console.log($("#picContent").val());
formData.append("file", img);
$.ajax({
data: formData,
url:"https://localhost:44340/home/upload",
type:"post",
data:formData,
processData: false,
contentType: false,
success:function(data){
alert(data);
}
})
})
</script>
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tiny Wang |