2
votes

How to upload all files in folder to Google Storage Cloud without loop. Here I try use C# with one file upload :

public async Task<ActionResult> Upload(IFormFile file)
{
    string contentRootPath = _hostingEnvironment.ContentRootPath;

    var credential = GoogleCredential.FromJson(System.IO.File.ReadAllText(contentRootPath + "/credentials.json"));

    StorageClient storageClient = StorageClient.Create(credential);

    var objectName = MakeObjectName();

    var imageObject = await storageClient.UploadObjectAsync(
        bucket: CloudConfig.BUCKET,
        objectName: objectName,
        contentType: file.ContentType,
        source: file.OpenReadStream(),
        options: new UploadObjectOptions { PredefinedAcl = PredefinedObjectAcl.PublicRead }
    );

    return Ok(new DropzoneInfo { Name = file.FileName, ObjectName = objectName, Link = imageObject.MediaLink, Size = file.Length});
}
1
Is there a problem with the code you have shown? - Llama
No problem with the code. Example only. - NguyenHung
then can you elaborate on the problem of extending this to multiple files? - Llama
I just want to question code in block upload to Google Cloud Storage. Not all code in Action. - NguyenHung
And what exactly is your question? At the moment I see a couple possibilities: a) you want to know how to get a list of files in a directory. b) you want to know how to loop through a list uploading each file. - Llama

1 Answers

1
votes

You have a controller action that accepts a single uploaded file. Use a List<IFormFile> in your controller action - see this answer: Submitting multiple files to ASP.NET controller accepting an ICollection<IFormFile>

There is an attribute for uploading directories: <input type="file" webkitdirectory> (How do I use Google Chrome 11's Upload Folder feature in my own code?)

These browsers support it: Edge, Safari, Firefox, Chrome, Opera (https://caniuse.com/#feat=input-file-directory)