dot net core upload zip file - empty file

77 Views Asked by At

I have a post to upload file and it is ok for pdf, txt, docx. When I try to upload zip file, I can't extract the files because the file is empty. Some ideas? Thanks in avance. public retOp UploadFile(IFormFile file) { try { string PathFile = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", Configuration.GetTempDir()); if (!Directory.Exists(PathFile)) { Directory.CreateDirectory(PathFile); } var formFile = file; if (formFile.Length > 0) { string fullPath = Path.Combine(PathFile, file.FileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { formFile.CopyToAsync(stream); } } .....

2

There are 2 best solutions below

1
On

I Think you should get Formfile from HttpContext.Request

public class UploadController: ControllerBase
{
    //this should be your uploadService
    private readonly IUploadService _uploadService;
    public UploadController(IUploadService uploadService)
    { _uploadService = uploadService; }

    [HttpPost("upload")]
    public IActionResult Upload()
    {
        //get file from Request
        var formFile = Request.Form.Files[0];
        _uploadService.UploadFile(formFile);
    }
}
0
On

The problem: the method was not async and I had a "stream.readtimeout". This is the change:

public async Task<retOp> UploadFileAsync(IFormFile file)
 {
  try    
    {
    ....
        using (var stream = new FileStream(fullPath, 
     FileMode.Create))
      {
       await formFile.CopyToAsync(stream);
     } ....

Best regards