編集:ちょうどあなたがtを持っていないことを確認o IEnumerable<byte>
を使用します。 byte[]
を使用すると正常に動作します。あなたはIEnumerable<byte>
と宣言することでバイトを受信できるように
WEBAPIは、IEnumerable<T>
にデシリアライズJSON配列をサポートしています。お使いのコントローラで
public class ImageModel
{
public string Name { get; set; }
public IEnumerable<byte> Bytes { get; set; }
}
:
次の例では、画像をアップロードする方法を示します。ディスクに画像を書き込む:
private string WriteImage(byte[] arr)
{
var filename = [email protected]"images\{DateTime.Now.Ticks}.";
using (var im = Image.FromStream(new MemoryStream(arr)))
{
ImageFormat frmt;
if (ImageFormat.Png.Equals(im.RawFormat))
{
filename += "png";
frmt = ImageFormat.Png;
}
else
{
filename += "jpg";
frmt = ImageFormat.Jpeg;
}
string path = HttpContext.Current.Server.MapPath("~/") + filename;
im.Save(path, frmt);
}
return [email protected]"http:\\{Request.RequestUri.Host}\{filename}";
}
HttpContext.Current.Server.MapPath("~/")
は、サーバーの内部パスを実行します。 Request.RequestUri.Host
はホスト名を返します。 AngularJSのため
<input type="file" id="imageFile"/>
アップロード方法:HTMLで
public IHttpActionResult UploadImage(ImageModel model)
{
var imgUrl = WriteImage(model.Bytes.ToArray());
// Some code
}
$scope.upload = function() {
var file = document.getElementById("imageFile").files[0];
var r = new FileReader();
r.onloadend = function (e) {
var arr = Array.from(new Uint8Array(e.target.result));
var uploadData = {
Name: "Name of Image",
Bytes: arr
}
console.log(uploadData);
$http.post('api/Uploader/UploadImage', uploadData)
.then(
function (response) {
console.log(response);
},
function (reason) {
console.log(reason);
})
}
r.readAsArrayBuffer(file);
}