Преобразование iFile в FileStream для загрузки в GoogleDrive работает, но файл имеет 0 байт (сервер Blazor)C#

Место общения программистов C#
Ответить
Anonymous
 Преобразование iFile в FileStream для загрузки в GoogleDrive работает, но файл имеет 0 байт (сервер Blazor)

Сообщение Anonymous »

Я могу «создать» файл на Google-Диске, используя приведенный ниже код, однако я заметил, что файлы имеют размер 0 байт. Я использую учетную запись службы, которая является редактором. Я использую элемент управления загрузкой Radzen.

Код: Выделить всё

     TrackProgress(args, "Single file upload")) class="w-100" InputAttributes="@(new Dictionary(){ { "aria-label", "select file" }})"> 
Контроллер, используемый для получения файла

Код: Выделить всё

[DisableRequestSizeLimit]
public partial class UploadController : Controller
{
private readonly IWebHostEnvironment environment;
private readonly GoogleDriveService _googleDriveService;

public UploadController(IWebHostEnvironment environment, GoogleDriveService googleDriveService)
{
this.environment = environment;
_googleDriveService = googleDriveService;
}

// Single file upload
[HttpPost("upload/volunteer")]
public IActionResult Volunteer(IFormFile file)
{
try
{
_googleDriveService.UploadFile(file, this.environment);

return StatusCode(200, file.FileName);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
}
Мой сервис для работы с Google Диском

Код: Выделить всё

public string UploadFile(IFormFile File, IWebHostEnvironment environment)
{
string uploadedFileId = "";

string RootFolderId = "xxxxxxxxxxxxxxxxxxxxxxxx";   \\Target Folder

var service = Auth();

try
{
FilesResource.CreateMediaUpload request;
using (var stream = new FileStream(Path.Combine(environment.WebRootPath, File.FileName), FileMode.Create))
{
using (MemoryStream memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File
{
Name = File.FileName,
Parents = new List { RootFolderId }
};
request = service.Files.Create(fileMetadata, memoryStream, File.ContentType);
request.Fields = "id";
request.SupportsTeamDrives = true;
request.SupportsAllDrives = true;
request.Upload();
}
}
Google.Apis.Drive.v3.Data.File file = request.ResponseBody;
uploadedFileId = file.Id;

return uploadedFileId;
}
catch (Exception ex)
{
var x = ex;
}

return uploadedFileId;
}

public DriveService Auth()
{
var credential = GoogleCredential.FromFile(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", PathToServiceAccountKeyFile))
.CreateScoped(DriveService.ScopeConstants.Drive);

// Create the  Drive service.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});

return service;
}
Мой код аутентификации для API

Код: Выделить всё

public DriveService Auth()
{
// Load the Service account credentials and define the scope of its access.
var credential = GoogleCredential.FromFile(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", PathToServiceAccountKeyFile))
.CreateScoped(DriveService.ScopeConstants.Drive);

// Create the  Drive service.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});

return service;
}
Загрузка выглядит так, будто все работает, файл создается на Google Диске в нужном месте, просто контента нет (0 байт)

Подробнее здесь: https://stackoverflow.com/questions/787 ... ut-the-fil
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»