【发布时间】:2019-05-18 10:54:05
【问题描述】:
我有一个文件,例如Parent.zip,解压缩后会生成以下文件:child1.jpg、child2.txt、child3.pdf。
通过下面的函数运行Parent.zip时,文件正确解压到:
some-container/child1.jpg
some-container/child2.txt
some-container/child3.pdf
如何将文件解压缩到其父文件夹?所需的结果是:
some-container/Parent/child1.jpg
some-container/Parent/child2.txt
some-container/Parent/child3.pdf
正如您在上面看到的,文件夹 Parent 已创建。
我正在使用它在 blob 中创建文件:
using (var stream = entry.Open ()) {
//check for file or folder and update the above blob reference with actual content from stream
if (entry.Length > 0) {
await blob.UploadFromStreamAsync (stream);
}
}
这是完整的来源:
[FunctionName ("OnUnzipHttpTriggered")]
public static async Task<IActionResult> Run (
[HttpTrigger (AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log) {
log.LogInformation ("C# HTTP trigger function processed a request.");
var requestBody = new StreamReader (req.Body).ReadToEnd ();
var data = JsonConvert.DeserializeObject<ZipFileMetaData> (requestBody);
var storageAccount =
CloudStorageAccount.Parse (Environment.GetEnvironmentVariable ("StorageConnectionString"));
var blobClient = storageAccount.CreateCloudBlobClient ();
var container = blobClient.GetContainerReference (data.SourceContainer);
var blockBlob = container.GetBlockBlobReference (data.FileName);
var extractcontainer = blockBlob.ServiceClient.GetContainerReference (data.DestinationContainer.ToLower ());
await extractcontainer.CreateIfNotExistsAsync ();
var files = new List<string> ();
// Save blob(zip file) contents to a Memory Stream.
using (var zipBlobFileStream = new MemoryStream ()) {
await blockBlob.DownloadToStreamAsync (zipBlobFileStream);
await zipBlobFileStream.FlushAsync ();
zipBlobFileStream.Position = 0;
//use ZipArchive from System.IO.Compression to extract all the files from zip file
using (var zip = new ZipArchive (zipBlobFileStream)) {
//Each entry here represents an individual file or a folder
foreach (var entry in zip.Entries) {
files.Add (entry.FullName);
//creating an empty file (blobkBlob) for the actual file with the same name of file
var blob = extractcontainer.GetBlockBlobReference (entry.FullName);
using (var stream = entry.Open ()) {
//check for file or folder and update the above blob reference with actual content from stream
if (entry.Length > 0) {
await blob.UploadFromStreamAsync (stream);
}
}
// TO-DO : Process the file (Blob)
//process the file here (blob) or you can write another process later
//to reference each of these files(blobs) on all files got extracted to other container.
}
}
}
return new OkObjectResult (files);
}
【问题讨论】:
-
在 blob 存储中,所有文件夹都是虚拟文件夹。因此,如果您创建一个名称为
Parent/child1.jpg的 blob,您将看到child1.jpg位于文件夹名称Parent下 -
@NafisIslam - 指出 Blob 存储根本没有文件夹可能是个好主意。整个层次结构是
blob-account/container/blob。看起来像文件夹的只是一个带有/分隔符的文件名。这实际上也在此处发布的答案中被提及。
标签: c# .net azure azure-functions azure-blob-storage