實現一個Web Api,把女友照片保存到Azure雲的storage裏。json
在對應的Api Controller裏,加上attribute:api
[Consumes("application/json", "multipart/form-data")]
而後定義一個model,用來接收上傳的圖片:瀏覽器
/// <summary> /// Image model /// </summary> public class UploadImage { /// <summary> /// imageFile /// </summary> public IFormFile imageFile { get; set; } }
實現對應的Api,處理客戶端上傳圖片的請求:app
/// <summary> /// UploadImage /// </summary> /// <param name="imageData"></param> /// <returns></returns> [HttpPost] [Route("imageupload")] public async Task<IActionResult> UploadImage([FromForm]UploadImage imageData) { var stream = imageData.imageFile.OpenReadStream(); var name = imageData.imageFile.FileName; var uploadResult = await UploadFileAsBlob(stream, name); return Ok(name); }
在Azure雲服務建立相應的Storage,並在對應的Storage下建一個Blob,最後在Blob裏建立一個Container,在storage的Access keys裏,保存connection string,這個是服務端鏈接storage的credential key。
由於如今的雲服務都是圖形化操做,這裏再也不詳述,在Portal都有對應的操做。async
引用兩個namespace:post
using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob;
鏈接Azure storage:spa
/// <summary> /// Save image to Azure blob /// </summary> /// <param name="stream"></param> /// <param name="filename"></param> /// <returns></returns> public async Task<string> UploadFileAsBlob(Stream stream, string filename) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse("StorageAccountConnectionString"); // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve a reference to a container. CloudBlobContainer container = blobClient.GetContainerReference("BlobContainerName"); CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename); await blockBlob.UploadFromStreamAsync(stream); stream.Dispose(); return blockBlob?.Uri.ToString(); }
選擇Body,在body裏選擇form-data,而後把key設置成model裏的變量名稱:3d
最後保存在Azure的storage中,code
在瀏覽器地址欄輸入storage 的地址+ 照片名稱,把女友的照片下載到本地。orm