C#到JS:如何用base64(RawBytes)图像格式附加img src?

时间:2017-07-11 16:25:11

标签: c# jquery asp.net-core httpresponse rest-client

我正在尝试将从bytes形式的API返回的图像传递到前端以附加到页面。

想要将图像保存在文件系统中,只是通过这种方式传递它。

回复的回复,但我对如何完成此过程感到迷茫。

这是我的API调用:

[HttpGet("api/GetCamImages")]
public async Task<HttpResponseMessage> ImageFromPath()
{
    RestClient client = new RestClient("http://MYIPADDRESS/cgi-bin/snapshot.cgi?channel=0");
    RestRequest request = new RestRequest(Method.GET);
    request.AddHeader("cache-control", "no-cache");
    request.AddHeader("authorization", "Basic YLKHSouHSSUGh2");
    TaskCompletionSource<IRestResponse> taskCompletion = new TaskCompletionSource<IRestResponse>();

    RestRequestAsyncHandle handle = client.ExecuteAsync(request, r => taskCompletion.SetResult(r));
    RestResponse restResponse = (RestResponse)(await taskCompletion.Task);
    StringContent myContent = new StringContent(Convert.ToBase64String(restResponse.RawBytes));

    var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);

    response.Content = myContent;
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");

    return response;
}

我的js:

 $http.get('/api/GetCamImages').then(function (response) {
    console.log(response.data);
    $("#imgContainer").append('<img src="data:image/png;base64,' + response.data.content + '" />');
});

上面的console.log显示了这个:

Console error

确认 - 我意识到上面的img src正在以[object, Object]出现,这就是图片无法显示的原因。但是你怎么能成功完成整个电话?

1 个答案:

答案 0 :(得分:0)

我能够使用两种方式解决这个问题(两者都取决于后端方法被改变了一点),其中一种方式使用RestSharp,另一种方式使用HttpClient

解决方案1:

RestClient client = new RestClient("http://MYIPADDRESS/cgi-bin/snapshot.cgi?channel=0");
RestRequest request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", "Basic YLKHSouHSSUGh2");
TaskCompletionSource<IRestResponse> taskCompletion = new TaskCompletionSource<IRestResponse>();
RestRequestAsyncHandle handle = client.ExecuteAsync(request, r => taskCompletion.SetResult(r));
response = (RestResponse)await taskCompletion.Task;

return "data:image/png;base64," + Convert.ToBase64String(response.RawBytes);

解决方案2:

HttpClient client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
HttpResponseMessage response = await client.GetAsync("http://MYIPADDRESS/cgi-bin/snapshot.cgi?channel=0");
byte[] myBytes = await response.Content.ReadAsByteArrayAsync();
string convertedFromString = Convert.ToBase64String(myBytes);

return "data:image/png;base64," + convertedFromString;