我正在使用jpeg_camera库从笔记本电脑上的 web 应用程序获取快照,并通过 fetch 调用将其发送到我的控制器。
snapshot.get_image_data
返回具有 3 个属性的对象(数据:Uint8ClampedArray、宽度、高度)。
当我进行 fetch 调用时,sendPic(data)
我总是会收到 400 错误,因为它ModelState
是无效的。
这意味着Byte[]
不适合Uint8ClampedArray
来自 JS。
该对象的等价物是什么?
我还发现了一种返回 base64 的方法,我可以在控制器内部将其转换为 aByte[]
但我想避免这种解决方案。
JS代码:
function savePic() {
var test1 = snapshot.get_image_data((done) => {
var data = {
"Pic": done.data,
"IdActivity": idActivity,
"Instant": new Date().toISOString()
};
sendPic(data);
});
}
function sendPic(data) {
fetch(uriPicsEndPoint, {
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json; charset=utf-8"
},
credentials: 'include',
method: 'POST'
});
}
API 控制器:
[Authorize]
[HttpPost]
public async Task<IActionResult> SavePic([FromBody] Selfie selfie)
{
if (ModelState.IsValid)
{
try
{
var storageAccount = CloudStorageAccount.Parse(_configuration["ConnectionStrings:Storage"]);
var blobClient = storageAccount.CreateCloudBlobClient();
var camerasContainer = blobClient.GetContainerReference("selfies");
await camerasContainer.CreateIfNotExistsAsync();
var id = Guid.NewGuid();
var fileExtension = ".jpeg";
var blobName = $"{selfie.IdActivity}/{id}{fileExtension}";
var blobRef = camerasContainer.GetBlockBlobReference(blobName);
await blobRef.UploadFromByteArrayAsync(selfie.Pic, 0, selfie.Pic.Length);
string sas = blobRef.GetSharedAccessSignature(
new SharedAccessBlobPolicy()
{
Permissions = SharedAccessBlobPermissions.Read
});
var blobUri = $"{blobRef.Uri.AbsoluteUri}{sas}";
var notification = new UpdateSelfieRequest()
{
UriPic = blobUri,
IdActivity = selfie.IdActivity,
Instant = selfie.Instant
};
string serviceBusConnectionString = _configuration["ConnectionStrings:ServiceBus"];
string queueName = _configuration["ServiceBusQueueName"];
IQueueClient queueClient = new QueueClient(serviceBusConnectionString, queueName);
var messageBody = JsonConvert.SerializeObject(notification);
var message = new Message(Encoding.UTF8.GetBytes(messageBody));
await queueClient.SendAsync(message);
await queueClient.CloseAsync();
return Ok();
}
catch
{
return StatusCode(500);
}
}
else
{
return BadRequest();
}
}
还有“自拍”类:
public class Selfie
{
public Byte[] Pic { get; set; }
public int IdActivity { get; set; }
public DateTime Instant { get; set; }
}