[英]File not streaming as expected in Asp.Net Core controller
I am trying to upload file to my onedrive, getting the file as expected seems streaming not process accordingly, could anyone please point me the problem.我正在尝试将文件上传到我的onedrive,按预期获取文件似乎没有相应地处理,谁能指出我的问题。
Code snippet:代码片段:
public async Task<IActionResult> UploadFileOnFolder(IFormFile uploadedFile, string folderName)
{
try
{
if (uploadedFile.Length > 0)
{
dynamic response;
var fileName = ContentDispositionHeaderValue.Parse(uploadedFile.FileName).FileName.Trim('"');
using var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(fileName));
response = await _graphServiceClient.Me.Drive.Items[folderName].Content
.Request()
.PutAsync<DriveItem>(stream);
ViewData["FileUploadInfo"] = response;
}
else
{
ViewData["message"] = "Sorry Upload failed! Please check your file!";
}
}
catch (Exception ex)
{
ViewData["message"] = ex.Message;
}
return RedirectToAction("RecentDirveInfo");
}
Note: I am following this official document.注意:我正在关注这个官方文档。
I am not sure about the APi, but I do know you are trying to upload the file name as the file.我不确定 APi,但我知道您正在尝试将文件名作为文件上传。 You will likely want to use uploadedFile.OpenReadStream
and instead pass that into PutAsync
您可能希望使用PutAsync
并将其传递给uploadedFile.OpenReadStream
Opens the request stream for reading the uploaded file.打开请求 stream 以读取上传的文件。
using var stream = uploadedFile.OpenReadStream();
response = await _graphServiceClient.Me.Drive.Items[folderName].Content
.Request()
.PutAsync<DriveItem>(stream);
Try the code below:试试下面的代码:
public async Task<IActionResult> UploadFileOnFolder(IFormFile uploadedFile, string folderName)
{
try
{
if (uploadedFile.Length > 0)
{
dynamic response;
var fileName = uploadedFile.FileName;
using var stream = uploadedFile.OpenReadStream();
response = await _graphServiceClient.Me.Drive.Root.ItemWithPath(folderName +"/" + fileName).Content.Request().PutAsync<DriveItem>(stream);
ViewData["FileUploadInfo"] = response;
}
else
{
ViewData["message"] = "Sorry check your file!";
}
}
catch (Exception ex)
{
ViewData["message"] = ex.Message;
}
return RedirectToAction("RecentDirveInfo");
}
I have tested it on my side it works for me perfectly:我已经对它进行了测试,它非常适合我:
Btw, make sure you have granted Delegated Permissions below to your Azure AD application before you run this code:顺便说一句,在运行此代码之前,请确保您已向 Azure AD 应用程序授予以下委派权限:
Files.ReadWrite, Files.ReadWrite.All, Sites.ReadWrite.All
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.