Home > Net >  Dotnet controller unable to save gif files
Dotnet controller unable to save gif files

Time:12-30

I'm making a converter that receives some image/video and does the process to turn it into a webp file.

With jpg, png and webm files i don't have any problem at all, but for some reason when I attempt to use a gif file I got this error: "Access to the path 'C:\Users\Desktop\computing\api\wwwroot\spin.gif' is denied."

This error occurs when i`m trying to save the file received by a IFormFile.

My controller is like this:

        [HttpPost]
        [DisableRequestSizeLimit]
        public async Task<IActionResult> ConverterToWebp()
        {
            var webp = new WEBPConverter(new VideoSettings(_videoSettings));

            var workingdir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
            var (file, _) = GetFile();

            if (file == null)
                return BadRequest("Arquivo inválido");

            var (filepath, _) = await SaveToDir(file, workingdir);

            var res = await webp.ConverterWebp(filepath);

            if (!res.Success)
                return BadRequest(res);

            return File(res.bytes, "image/webp");
        }

The method GetFile() look like this:

        private (IFormFile? file, string? mimetype) GetFile()
        {
            var files = HttpContext.Request.Form.Files;
            var file = files.FirstOrDefault();

            if (file == null || file.Length == 0)
                return (null, null);

            var contentTypeProvider = new FileExtensionContentTypeProvider();

            var isBlob = file.FileName.ToLower() == "blob";
            var mimetypeParseOk = contentTypeProvider.TryGetContentType(file.FileName, out var mimeType);

            if (isBlob)
                return (file, "blob");

            if (mimetypeParseOk)
                return (file, mimeType);

            return (null, null);
        }

And the method who trigger the error, SaveToDir(), look like this:

       private async Task<(string filepath, string filename)> SaveToDir(IFormFile file, string path)
        {
            var filename = new string(file.FileName
                .Replace(' ', '_')
                .Normalize(NormalizationForm.FormD)
                .Where(ch => char.GetUnicodeCategory(ch) != UnicodeCategory.NonSpacingMark)
                .ToArray());

            var filepath = Path.Combine(path, filename);

            using var stream = new FileStream(filepath, FileMode.Create);

            await file.CopyToAsync(stream);

            return (filepath, filename);
        }

The entire project is using .net core 6.0

If I take one file with .gif extension and change it to .webm I got no error, even though the conversion don`t works great.

I don't know the reason why only if i use gif this method to save in directory don't work and generate that generic error because the path exist and has permissions, and that's why it doesn't trigger error in other files types.

CodePudding user response:

By default IIS does not have permission for the wwwroot folder. You need to grant permissions to the IIS_IUSRS for the folder. I would not recommend this approach as it may be a potential security risk. The approach you could take is:

string path = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());

With this you would save the file to the temp folder and temp file name in the users temp folder, in this case the assigned application user or by default IIS_IUSRS. Don't forget to delete the file after you're done with it.

In the case you want to go with the path of granting the access you do the following:

  • Go to where your inetpub folder is located
  • Right click on wwwroot and click on Properties
  • Switch to the security tab and click Edit...
  • Look for the IIS_IUSRS user, should be PCNAME\IIS_IUSRS
  • Select Allow for all permissions.

CodePudding user response:

In the end I managed to solve the problem by saving a file without extesion and using theirs bytes arrays to convert.

But in fact the original question is not solved, any file that I try to use and that has the gif's extension get error. I tried to test changing a webm file that's working with name "test.webm" to "test.gif" and get the same error of permission.

This is how my method got no error:

    private async Task<(string filepath, string filename)> SaveToDir(IFormFile file, string path)
    {
        var timespanEpoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

        var filename = $"web_temp_file-{timespanEpoch}";

        var filepath = Path.Combine(path, filename);

        using var stream = new FileStream(filepath, FileMode.Create);

        await file.CopyToAsync(stream);

        return (filepath, filename);
    }
  • Related