Esempio n. 1
0
    public async Task <IActionResult> UploadImage(List <IFormFile> file)
    {
        // Create an unique folder path to help with concurrent users to avoid filename clash
        var imageTempPath =
            _hostingEnvironment.MapPathWebRoot(Constants.SystemDirectories.TempImageUploads + "/" + Guid.NewGuid());

        // Ensure image temp path exists
        if (Directory.Exists(imageTempPath) == false)
        {
            Directory.CreateDirectory(imageTempPath);
        }

        // Must have a file
        if (file.Count == 0)
        {
            return(NotFound());
        }

        // Should only have one file
        if (file.Count > 1)
        {
            return(new UmbracoProblemResult("Only one file can be uploaded at a time", HttpStatusCode.BadRequest));
        }

        IFormFile formFile = file.First();

        // Really we should only have one file per request to this endpoint
        //  var file = result.FileData[0];
        var fileName     = formFile.FileName.Trim(new[] { '\"' }).TrimEnd();
        var safeFileName = fileName.ToSafeFileName(_shortStringHelper);
        var ext          = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLowerInvariant();

        if (_contentSettings.IsFileAllowedForUpload(ext) == false ||
            _imageUrlGenerator.IsSupportedImageFormat(ext) == false)
        {
            // Throw some error - to say can't upload this IMG type
            return(new UmbracoProblemResult("This is not an image filetype extension that is approved", HttpStatusCode.BadRequest));
        }

        var newFilePath         = imageTempPath + Path.DirectorySeparatorChar + safeFileName;
        var relativeNewFilePath = _ioHelper.GetRelativePath(newFilePath);

        await using (FileStream stream = System.IO.File.Create(newFilePath))
        {
            await formFile.CopyToAsync(stream);
        }

        return(Ok(new { tmpLocation = relativeNewFilePath }));
    }