我有一个带有blob(/images/filename(的Azure存储容器。文件名(uri(在创建时存储在数据库中,来自文件上传保存函数:
blob.UploadFromStream(filestream);
string uri = blob.Uri.AbsoluteUri;
return uri;
文件上传工作正常,当使用 SAS 密钥下载传递给客户端时也可以正常工作。
来删除图像我有一个辅助函数,该函数取自此处的 MS 示例:MS Github 示例 这是函数:
internal bool DeleteFile(string fileURI)
{
try
{
Uri uri = new Uri(fileURI);
string filename = Path.GetFileName(uri.LocalPath);
CloudBlockBlob fileblob = container.GetBlockBlobReference(filename);
fileblob.Delete();
bool res = fileblob.DeleteIfExists();
return res; //Ok
}
catch(Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
这一切都在一个帮助程序类中,该类的开头如下所示:
public class AzureHelpers
{
private string connection;
private CloudStorageAccount storageAccount;
private CloudBlobClient blobClient;
private CloudBlobContainer container;
public AzureHelpers()
{
connection = CloudConfigurationManager.GetSetting("myproject_AzureStorageConnectionString");
storageAccount = CloudStorageAccount.Parse(connection);
blobClient = storageAccount.CreateCloudBlobClient();
container = blobClient.GetContainerReference(Resources.DataStoreRoot);
container.CreateIfNotExists();
}
....
我故意在 deleteIfExists 之前添加了删除,以引起异常并证明我怀疑它没有找到文件/blob。
然而,当我逐步完成代码时,CloudBlockBlob肯定在那里并且具有正确的URI等。
我想知道这是否可能是权限的事情?还是我错过了别的东西?
我认为您的容器中有一个目录。假设您有一个名为container_1
的容器,并且您的文件存储在类似/images/a.jpg
的目录中。在这里,您应该记住,在这种情况下,您的 blob 名称是images/a.jpg
,而不是a.jpg
。
在您的代码中,Path.GetFileName
只获取像a.jpg
这样的文件名,因此它与真正的 blob 名称不匹配images/a.jpg
,这会导致错误"不存在"。
所以在你的DeleteFile(string fileURI)
方法中,试试下面的代码,它在我身边工作正常:
Uri uri = new Uri(fileURI);
var temp = uri.LocalPath;
string filename = temp.Remove(0, temp.IndexOf('/', 1)+1);
CloudBlockBlob fileblob = container.GetBlockBlobReference(filename);
//fileblob.Delete();
bool res = fileblob.DeleteIfExists();
或使用以下代码片段:
Uri uri = new Uri(fileURI);
//use this line of code just to get the blob name correctly
CloudBlockBlob blob_temp = new CloudBlockBlob(uri);
var myblob = cloudBlobContainer.GetBlockBlobReference(blob_temp.Name);
bool res = myblob.DeleteIfExists();
似乎是一个权限问题,是否可以转到门户,然后编辑 Azure bolb 存储上的容器元数据。 将"专用访问权限"更改为">public
"。