I'm facing an issue with uploading a file via the Drag'n Drop API. Here the following blazor component:
<InputTextArea
@ondrop="HandleDrop"
@ondragenter="HandleDragEnter"
@ondragleave="HandleDragLeave"/>
</InputTextArea>
@code {
private async Task HandleDrop(DragEventArgs args)
{
var files = args.DataTransfer.Files;
// Do something to upload the file and get the content
}
I want to upload the file and display it in the textarea. Now since .NET6 the DragEventArgs will list all files (if any) associated with the Drag'n Drop event.
Natively there seems to be no way to get the content of those files.
Therefore I tried to achieve this with JavaScript interop:
private async Task HandleDrop(DragEventArgs args)
{
var content = await jsRuntime.InvokeAsync<string>("getContentFromFile", args);
}
With the following JavaScript function (which is referenced in the _Layout.cshtml):
async function getContentFromFile(args) {
// Use some API here? File Upload API? Didn't work as args is only a data object and not the "real" DragEventArgs from JavaScript
// I also tried FileReader
const fileName = args.Files[0]; // Let's assume we always have one file
let content = await new Promise((resolve) => {
let fileReader = new FileReader();
fileReader.onload = (e) => resolve(fileReader.result);
fileReader.readAsText(fileName);
});
console.log(content);
return content;
}
This approach let to other issues and exceptions, like that the FileReader threw:
parameter is not of type 'Blob'
Is this with this approach with the current version of blazor (.net6) possible at all? Any tips are welcome.
<InputFile OnChange="@LoadFilesAsync" multiple/>into the razor and aprivate async Task LoadFilesAsync(InputFileChangeEventArgs e) { foreach (var file in e.GetMultipleFiles(5)){ Stream stream = file.OpenReadStream(2048000);in the code, it started uploading when i dropped a file on the "Choose files" button (the only visible part of the inputfile)..