1

I am using AWS S3 SDK and I want to upload the files from my WEB API to the Bucket. It is working perfectly normal if the provided filePath is of the sort C:\User\Desktop\file.jpg, but if I use Path.GetFullPath(file.FileName) It is looking for the .jpg file inside my project folder. How can I get the absolute path on the machine, not the path in the project folder.

public async Task UploadFileAsync(IFormFile file, string userId)
    {
        var filePath = Path.GetFullPath(file.FileName);
        var bucketName = this.configuration.GetSection("Amazon")["BucketName"];
        var accessKey = this.configuration.GetSection("Amazon")["AWSAccessKey"];
        var secretKey = this.configuration.GetSection("Amazon")["AWSSecretKey"];
        var bucketRegion = RegionEndpoint.EUWest1;

        var s3Client = new AmazonS3Client(accessKey, secretKey, bucketRegion);

        try
        {
            var fileTransferUtility =
                new TransferUtility(s3Client);

            using (var fileToUpload =
                  new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                await fileTransferUtility.UploadAsync(fileToUpload, bucketName, file.FileName);
            }

            await this.filesRepository.AddAsync(new FileBlob
            {
                Name = file.FileName, 
                Extension = file.FileName.Split('.')[1],
                Size = file.Length,
                UserId = userId,
                UploadedOn = DateTime.UtcNow,
            });
            await this.filesRepository.SaveChangesAsync();
        }
        catch (AmazonS3Exception e)
        {
            Console.WriteLine(e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

path i get when i use GetFullPath when i should be getting C:\Users\Pepi\Desktop\All\corgi.png

I am sure that I am missing a lot of things here but in order for it to work i need the path to the file on the machine. If i try to escape using filepath and upload the file itself through memoryStream S3 says access denied.

DrinkBlink
  • 107
  • 1
  • 8
  • If you know the path then why are you using `Path.GetFullPath`? Please show us your code for IFile. You have to put the path somewhere, either in `IFile` or in a config and read it from there. It is not possible for `Path` to know where your file is. – CodingYoshi May 24 '20 at 13:10
  • Many examples available [here](https://stackoverflow.com/questions/13342123/how-to-get-relative-path-of-a-file-in-visual-studio). – CodingYoshi May 24 '20 at 13:21
  • There is a user form which accepts file from the user's machine. [Here](https://res.cloudinary.com/dnonuly2u/image/upload/v1590328344/Screenshot_1_l3oqil.png) . What I want to do is, once the user has chosen a file, to upload it on the S3 bucket. And since AWSSDK requires file path, I dont know how to give the full machine path. – DrinkBlink May 24 '20 at 13:54

0 Answers0