Efficient way to Unzip a File received through HttpPost without Unzip in Memory or File System and upload the File to Box
twiga2013 opened this issue · comments
Hi,
I need guidance on a best way to accomplish the following
- I will be receiving a zip file through an API
- I need to upload the content of the zip to Box
I want to avoid using server memory or temporary file location to unzip and then upload the file to box. What is the best way to go about doing this. I am using .NET Core.
Here is the initial code I have where I am unzipping it to temp location
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
string modelString = JsonConvert.SerializeObject(model);
request.Content = new StringContent(modelString, System.Text.Encoding.UTF8, "application/json");
string filetemppath = string.Empty;
string filename = string.Empty;
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
using (ZipArchive archive = new ZipArchive(await response.Content.ReadAsStreamAsync()))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
using (Stream stream = entry.Open())
{
filename = entry.Name;
filetemppath = Path.Combine(Path.GetTempFileName());
using (FileStream file = new FileStream(filetemppath, FileMode.Create, FileAccess.Write))
{
await stream.CopyToAsync(file);
}
}
}
}
Hi @twiga2013
Because entry.Open() returns a DeflatedStream
which doesn't support Length and Position property we need to use other stream class here.
So a good solution here is to use a temp file and a FileStream like you did in your code.
Here is an example on working code:
using (var archive = new ZipArchive(file))
{
foreach (ZipArchiveEntry entry in archive.Entries)
{
using (Stream stream = entry.Open())
{
var filePath = Path.GetTempFileName();
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
{
await fs.CopyToAsync(fs);
fs.Seek(0, SeekOrigin.Begin);
var fileRequest = new BoxFileRequest
{
Name = entry.Name,
Parent = new BoxFolderRequest { Id = "<folder_id>" }
};
var bFile = await client.FilesManager.UploadAsync(fileRequest, fs);
Console.WriteLine($"File {entry.Name} was uploaded successfully with id {bFile.Id}");
}
}
}
}
Hope this help!
This issue has been automatically marked as stale because it has not been updated in the last 30 days. It will be closed if no further activity occurs within the next 7 days. Feel free to reach out or mention Box SDK team member for further help and resources if they are needed.
This issue has been automatically closed due to maximum period of being stale. Thank you for your contribution to Box .NET SDK and feel free to open another PR/issue at any time.