Search code examples
file-ioasp.net-core-mvczip

How to save zip compressed folder to disk asp.net core 3.0


I want to upload and save a zipped folder to a path on my disk drive using .net core 3.0 but the zipped folder is saving as 0bytes

[HttpPost]
    [ValidateAntiForgeryToken()]
    [RequestFormLimits(MultipartBodyLengthLimit = 20971520)]//max size should be 20MB
    public IActionResult AddFile(List<IFormFile> files)
    {
        IActionResult ar = null;
        try
        {

            if (id != 0)
            {
                foreach(var singlefile in files)
                {
                    var ext = Path.GetExtension(singlefile.FileName).ToLowerInvariant();


                        //begin saving procedure
                        if(singlefile.Length > 0 && singlefile.Length <= Convert.ToInt32(_config.Value.FileSizeLimit))
                        {
                            var filepath = Path.Combine(_config.Value.StoredFilesPath, Path.GetRandomFileName().Split('.')[0] + ext);


                                using(var stream = System.IO.File.Create(filepath))
                                {
                                    singlefile.CopyToAsync(stream);
                                }

                        }

                }
        }
        catch (Exception e)
        {
            _log.Error(e);                
        }
        return ar;
    }

Please What am i missing out? I can save files with other extensions using this same piece of code, it saves and i can view properly but only .zip files saves as 0bytes


Solution

  • You didn't wait for the copy task to complete. Try change the method to an async action:

    public async Task<IActionResult> AddFile(List<IFormFile> files)
    {
        ...
        using(var stream = System.IO.File.Create(filepath))
        {
            await singlefile.CopyToAsync(stream); // await here, otherwise the stream is disposed quickly
        }
        ...
    }