2

我正在使用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; }
}
4

1 回答 1

0

当您使用 stringify 时,它会变成{"0":255, "1":0, "2":0, "3":255, ...}JSON。

如果您将操作参数定义为JObject selfie可以使用var pic = selfie["Pic"].ToObject<Dictionary<int, byte>>().

或者,您可以将数据作为表单值发布,并将操作定义为SavePic(Dictionary<int, byte> Pic, int IdActivity, DateTime Instant)在浏览器中使用以下代码进行测试:

var ctx = document.createElement('canvas').getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(5, 5, 5, 5);

$.post('SavePic', {
    Pic: ctx.getImageData(5, 5, 5, 5).data,
    IdActivity: 1,
    Instant: new Date().toISOString()
});

但是,在发布数据之前将 Uint8ClampedArray 转换为常规数组可能更容易。

于 2018-07-13T22:11:27.240 回答