![](/img/trans.png)
[英]how to upload the image into azure storage blob using angualr2 and typescript
[英]Upload the image into storage blob using typescript and angular2
我正在使用打字稿開發角度2應用程序。 在我目前的項目中,我實現了將圖像上傳到azure存儲blob的功能,為此我按照下面的鏈接。
http://www.ojdevelops.com/2016/05/end-to-end-image-upload-with-azure.html
我為我的視圖編寫下面的代碼行,從本地機器中選擇圖像。
<form name="form" method="post">
<div class="input-group">
<input id="imagePath" class="form-control" type="file" name="file" accept="image/*" />
<span class="input-group-btn">
<a class="btn btn-success" (click)='uploadImage()'>Upload</a>
<!--href="../UploadImage/upload"-->
<!--(click)='uploadImage()'-->
</span>
</div>
</form>
當我點擊上傳按鈕時,在uploadcomponent.ts文件中,我編寫了以下代碼行,用於發送http post請求以及內容作為選定的圖像路徑。
uploadImage(): void {
//var image = Request["imagePath"];
//alert('Selected Image Path :' + image);
this.imagePathInput = ((<HTMLInputElement>document.getElementById("imagePath")).value);
alert('Selected Image Path :' + this.imagePathInput);
let imagePath = this.imagePathInput;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');//application/x-www-form-urlencoded
this._http.post('/UploadImage/UploadImagetoBlob', JSON.stringify(imagePath),
{
headers: headers
})
.map(res => res.json())
.subscribe(
data => this.saveJwt(data.id_token),
err => this.handleError(err),
() => console.log('ImageUpload Complete')
);
}
UploadImageController.cs
在UploadImageController.cs文件中,我在下面寫下代碼行,將圖像上傳到azure storage blob。
[HttpPost]
[Route("UploadImage/UploadImagetoBlob")]
public async Task<HttpResponseMessage> UploadImagetoBlob()
{
try
{
//WebImage image = new WebImage("~/app/assets/images/AzureAppServiceLogo.png");
//image.Resize(250, 250);
//image.FileName = "AzureAppServiceLogo.png";
//img.Write();
var image = WebImage.GetImageFromRequest();
//WebImage image = new WebImage(imagePath);
var imageBytes = image.GetBytes();
// The parameter to the GetBlockBlobReference method will be the name
// of the image (the blob) as it appears on the storage server.
// You can name it anything you like; in this example, I am just using
// the actual filename of the uploaded image.
var blockBlob = blobContainer.GetBlockBlobReference(image.FileName);
blockBlob.Properties.ContentType = "image/" + image.ImageFormat;
await blockBlob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length);
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("../app/upload/uploadimagesuccess.html", UriKind.Relative);
//return Ok();
return response;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
在上面的控制器代碼中,下面的行代碼總是給出空值。
var image = WebImage.GetImageFromRequest();
你能告訴我如何解決上述問題嗎?
-Pradeep
經過大量研究后,我得到了結果。 以下鏈接對於將所選圖像上載到服務器或Azure存儲blob非常有用。 對於我的場景,我將選定的圖像上傳到azure存儲blob中。
https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/
http://www.ojdevelops.com/2016/05/end-to-end-image-upload-with-azure.html
這是我的UploadImage.Component.html
<form name="form" method="post" action="" enctype="multipart/form-data">
<div class="input-group">
<input id="imagePath" class="form-control" type="file" (change)="fileChangeEvent($event)" name="Image" accept="image/*" />
<span class="input-group-btn">
<a class="btn btn-success" (click)='uploadImagetoStorageContainer()'>Upload</a>
</span>
</div>
這是我的UploadImage.Component.ts
/////////////////////////////////////////////////////////////////////////////////////
// calling UploadingImageController using Http Post request along with Image file
//////////////////////////////////////////////////////////////////////////////////////
uploadImagetoStorageContainer() {
this.makeFileRequest("/UploadImage/UploadImagetoBlob", [], this.filesToUpload).then((result) => {
console.log(result);
}, (error) => {
console.error(error);
});
}
makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
for (var i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert("successfully uploaded image into storgae blob");
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", url, true);
xhr.send(formData);
});
}
fileChangeEvent(fileInput: any) {
this.filesToUpload = <Array<File>>fileInput.target.files;
}
這是我的UploadImageController.ts
[HttpPost]
[Route("UploadImage/UploadImagetoBlob")]
public async Task<IHttpActionResult> UploadImagetoBlob()//string imagePath
{
try
{
//var iamge= imagePath as string;
//WebImage image = new WebImage("~/app/assets/images/AzureAppServiceLogo.png");
//image.Resize(250, 250);
//image.FileName = "AzureAppServiceLogo.png";
//img.Write();
var image =WebImage.GetImageFromRequest();
//WebImage image = new WebImage(imagePath);
//var image = GetImageFromRequest();
var imageBytes = image.GetBytes();
// The parameter to the GetBlockBlobReference method will be the name
// of the image (the blob) as it appears on the storage server.
// You can name it anything you like; in this example, I am just using
// the actual filename of the uploaded image.
var blockBlob = blobContainer.GetBlockBlobReference(image.FileName);
blockBlob.Properties.ContentType = "image/" + image.ImageFormat;
await blockBlob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length);
//var response = Request.CreateResponse(HttpStatusCode.Moved);
//response.Headers.Location = new Uri("../app/upload/uploadimagesuccess.html", UriKind.Relative);
//return response;
return Ok();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
這個答案可能有助於誰正在尋找使用角度2應用程序中的typescript將所選圖像上傳到azure存儲blob的功能。
問候,
普拉迪普
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.