前言
实现一个Web Api,把女朋友照片保存到Azure云的storage里。
Image Upload Api
在对应的Api Controller里,加上attribute:
[Consumes("application/json", "multipart/form-data")]
然后定义一个model,用来接收上传的图片:
/// <summary>
/// Image model
/// </summary>
public class UploadImage
{
/// <summary>
/// imageFile
/// </summary>
public IFormFile imageFile { get; set; }
}
实现对应的Api,处理客户端上传图片的请求:
/// <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);
}
创建Storage
在Azure云服务创建相应的Storage,并在对应的Storage下建一个Blob,最后在Blob里创建一个Container,在storage的Access keys里,保存connection string,这个是服务端连接storage的credential key。
因为现在的云服务都是图形化操作,这里不再详述,在Portal都有对应的操作。
保存图片在Blob中
引用两个namespace:
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
连接Azure storage:
/// <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();
}
Postman上传效果
选择Body,在body里选择form-data,然后把key设置成model里的变量名称:
最后保存在Azure的storage中,
在浏览器地址栏输入storage 的地址+ 照片名称,把女朋友的照片下载到本地。
原文地址:https://www.cnblogs.com/shy-huang/p/9896726.html
时间: 2024-10-17 16:21:32