c# - 将图片从 webapi 上传到 blob 存储时,如何验证扩展名和图片大小?
问题描述
我有以下代码来上传图片,使用 guid 重命名并更新 POCO 个人资料图片 URL。
但是我需要一些额外的验证 1. 只允许 png 文件 2. 最大 200x200 (并且图片应该是平方的)
但是我不确定如何满足这 2 个要求。
[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);
}
}
解决方案
尝试使用以下代码:
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
}
}
}
推荐阅读
- python - 使用 Tensorflow 嵌入列会引发 All feature_columns must be _FeatureColumn instances 错误
- javascript - 切换时无法更改卡片的背景颜色
- c++ - 使用指针从dll调用函数不起作用
- embed - 制作单个 exe cefsharp 应用程序 - 嵌入 libcef.dll - costura.fody
- php - 如何在 php 环境中使用 Sql 查询逐行读取文本文件(UTF-8)并将数据放入 Sql 数据库文件
- vb.net - 将列值添加到一行
- geometry - 距离度量不同的单位
- visual-studio - 无法使用 Visual Studio 2019 和 Azure 发布 Web 应用程序
- python - 如何在 Python 中使用输入文件(bash 命令)运行二进制可执行文件?
- python - Pytest 如何在范围“类”中包含“设置”固定装置