我正在使用以下代码将图像上传到Azure blob存储。图片已上传到存储设备,但已损坏。以下是我的代码。 Base64字符串正确,我已经确认。
string match_val = "z5FuyuNiJDbbb...................";
System.Drawing.Bitmap img = Custom.ConertBase64ToFile(match_val);
var bytes = Convert.FromBase64String(match_val);
StorageCredentials creden = new StorageCredentials(accountname, accesskey);
CloudStorageAccount acc = new CloudStorageAccount(creden, useHttps: true);
CloudBlobClient client = acc.CreateCloudBlobClient();
CloudBlobContainer cont = client.GetContainerReference(container);
await cont.CreateIfNotExistsAsync();
await cont.SetPermissionsAsync(new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
CloudBlockBlob cblob = cont.GetBlockBlobReference(Path.Combine(ProfileSignaturePath, string.Concat(fileName, ".", FileFormat.png)).Replace(@"\","/"));
cblob.Properties.ContentType = "image/png";
using (System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(bytes), true, true))
{
using (MemoryStream memoryStream = new MemoryStream())
{
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
await cblob.UploadFromStreamAsync(memoryStream);
blobUrl = cblob.Uri.AbsoluteUri;
}
}
string resUrl = blobUrl;
这是浏览器显示的内容
我的图片上传代码中是否存在任何问题?
答案 0 :(得分:0)
我可以知道match_val是什么吗?它是png文件内容的base64编码的字符串吗?
我迅速创建了一个控制台项目,并且一切正常。这是我的示例:
class Program
{
static string storageAccountName = "storagetest789";
static string storageAccountKey = "G36mc********Zup3h9kzj1w==";
static void Main(string[] args)
{
string match_val = null;
using(FileStream fileStream = File.Open(@"D:\User\Pictures\test.png",FileMode.Open))
using(MemoryStream memoryStream = new MemoryStream()){
fileStream.CopyTo(memoryStream);
match_val = Convert.ToBase64String(memoryStream.ToArray());
}
StorageCredentials storageCredentials = new StorageCredentials(storageAccountName,storageAccountKey);
CloudStorageAccount cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("pub"); // For convenience, it is a public container, so I do not need to set access permission
cloudBlobContainer.CreateIfNotExists();
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference("test2.png");
using(MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(match_val)))
using(Image image = Image.FromStream(memoryStream,true,true))
using(CloudBlobStream cloudBlobStream = cloudBlockBlob.OpenWrite()){
image.Save(cloudBlobStream, System.Drawing.Imaging.ImageFormat.Png);
}
Console.WriteLine(cloudBlockBlob.Uri.AbsoluteUri);
Console.ReadLine();
}
}
我没有base64编码的字符串。所以我在代码中生成了一个。区别在于:
cloudBlockBlob.OpenWrite()
打开了一个输出流最后,我得到一个网址:https://storagetest789.blob.core.windows.net/pub/test2.png