C# 将图像从webapi上载到blob存储时,如何验证扩展名和图片大小?
我有以下代码来上传图片,用guid重命名它,并更新POCO配置文件图片URL 然而,我需要一些额外的验证 1.只允许使用png文件 2.最大200x200(图片应为正方形) 然而,我不知道如何做到这两个要求C# 将图像从webapi上载到blob存储时,如何验证扩展名和图片大小?,c#,asp.net,.net,asp.net-web-api,azure-blob-storage,C#,Asp.net,.net,Asp.net Web Api,Azure Blob Storage,我有以下代码来上传图片,用guid重命名它,并更新POCO配置文件图片URL 然而,我需要一些额外的验证 1.只允许使用png文件 2.最大200x200(图片应为正方形) 然而,我不知道如何做到这两个要求 [HttpPut] public async Task<IHttpActionResult> UpdateUser(User user) { var telemetry = new TelemetryClient();
[HttpPut]
public async Task<IHttpActionResult> UpdateUser(User user)
{
var telemetry = new TelemetryClient();
try
{
//First we validate the model
var userStore = CosmosStoreHolder.Instance.CosmosStoreUser;
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//Then we validate the content type
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
//Initalize configuration settings
var accountName = ConfigurationManager.AppSettings["storage:account:name"];
var accountKey = ConfigurationManager.AppSettings["storage:account:key"];
var profilepicturecontainername = ConfigurationManager.AppSettings["storage:account:profilepicscontainername"];
//Instance objects needed to store the files
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer imagesContainer = blobClient.GetContainerReference(profilepicturecontainername);
var provider = new AzureStorageMultipartFormDataStreamProvider(imagesContainer);
//Try to upload file
try
{
await Request.Content.ReadAsMultipartAsync(provider);
}
catch (Exception ex)
{
string guid = Guid.NewGuid().ToString();
var dt = new Dictionary<string, string>
{
{ "Error Lulo: ", guid }
};
telemetry.TrackException(ex, dt);
return BadRequest($"Error Lulo. An error has occured. Details: {guid} {ex.Message}: ");
}
// Retrieve the filename of the file you have uploaded
var filename = provider.FileData.FirstOrDefault()?.LocalFileName;
if (string.IsNullOrEmpty(filename))
{
string guid = Guid.NewGuid().ToString();
var dt = new Dictionary<string, string>
{
{ "Error Lulo: ", guid }
};
return BadRequest($"Error Lulo. An error has occured while uploading your file. Please try again.: {guid} ");
}
//Rename file
CloudBlockBlob blobCopy = imagesContainer.GetBlockBlobReference(user.Id+".png");
if (!await blobCopy.ExistsAsync())
{
CloudBlockBlob blob = imagesContainer.GetBlockBlobReference(filename);
if (await blob.ExistsAsync())
{
await blobCopy.StartCopyAsync(blob);
await blob.DeleteIfExistsAsync();
}
}
user.ProfilePictureUrl = blobCopy.Name;
var result = await userStore.UpdateAsync(user);
return Ok(result);
}
catch (Exception ex)
{
string guid = Guid.NewGuid().ToString();
var dt = new Dictionary<string, string>
{
{ "Error Lulo: ", guid }
};
telemetry.TrackException(ex, dt);
return BadRequest("Error Lulo: " + guid);
}
}
[HttpPut]
公共异步任务更新器(用户)
{
var telemetry=新遥测客户端();
尝试
{
//首先,我们验证模型
var userStore=CosmosStoreHolder.Instance.CosmosStoreUser;
如果(!ModelState.IsValid)
{
返回请求(ModelState);
}
//然后验证内容类型
if(!Request.Content.IsMimeMultipartContent(“表单数据”))
{
抛出新的HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
//初始化配置设置
var accountName=ConfigurationManager.AppSettings[“存储:帐户:名称”];
var accountKey=ConfigurationManager.AppSettings[“存储:帐户:键”];
var profilepicturecontainername=ConfigurationManager.AppSettings[“存储:帐户:profilepicscontainername”];
//存储文件所需的实例对象
var-storageAccount=new-CloudStorageAccount(new-StorageCredentials(accountName,accountKey),true);
CloudBlobClient blobClient=storageAccount.CreateCloudBlobClient();
CloudBlobContainer imagesContainer=blobClient.GetContainerReference(profilepicturecontainername);
var provider=新AzureStorageMultipartFormDataStreamProvider(imagesContainer);
//尝试上载文件
尝试
{
wait Request.Content.ReadAsMultipartAsync(提供程序);
}
捕获(例外情况除外)
{
字符串guid=guid.NewGuid().ToString();
var dt=新字典
{
{“错误Lulo:,guid}
};
遥测.跟踪异常(ex,dt);
返回BADDREQUEST($”错误Lulo。发生错误。详细信息:{guid}{ex.Message}:”;
}
//检索已上载文件的文件名
var filename=provider.FileData.FirstOrDefault()?.LocalFileName;
if(string.IsNullOrEmpty(文件名))
{
字符串guid=guid.NewGuid().ToString();
var dt=新字典
{
{“错误Lulo:,guid}
};
返回BADDREQUEST($”错误Lulo。上载文件时出错。请重试。:{guid});
}
//重命名文件
CloudBlockBlob blobCopy=imagesContainer.GetBlockBlobReference(user.Id+“.png”);
如果(!wait blobCopy.ExistsAsync())
{
CloudBlockBlob blob=imagesContainer.GetBlockBlobReference(文件名);
if(等待blob.ExistsAsync())
{
等待blobCopy.startCopySync(blob);
等待blob.DeleteIfExistsAsync();
}
}
user.ProfilePictureUrl=blobCopy.Name;
var result=await userStore.UpdateAsync(用户);
返回Ok(结果);
}
捕获(例外情况除外)
{
字符串guid=guid.NewGuid().ToString();
var dt=新字典
{
{“错误Lulo:,guid}
};
遥测.跟踪异常(ex,dt);
返回BADDREQUEST(“错误Lulo:+guid”);
}
}
尝试使用以下代码:
foreach (MultipartFileData file in provider.FileData)
{
var fileName = file.Headers.ContentDisposition.FileName.Trim('\"').Trim();
if (fileName.EndsWith(".png"))
{
var img = Image.FromFile(file.LocalFileName);
if (img.Width == 200 && img.Height == 200)
{
//here is ur logic
}
}
}
可能重复,但不是重复,因为使用Azure Blob存储SDK与上述问题/答案不同。请在上载之前检查。blob中没有文件,只有一些二进制数据