Pandiyaraj
Pandiyaraj

Reputation: 36

Blazor - ondrop event doesn't return file object

I have bind @ondrop event into my div element, while drag and drop local image into div, DragEventArgs doesn't return file object details.

Razor code

<div @ondrop="@OnDrop"></div>

@code{
    internal void OnDrop(DragEventArgs args)
    {
        var files = args.DataTransfer.Files;
    }
}

output:

image

Anyone have solution for this case?

Note: My main goal is to convert it as FileStream or MemoryStream then save it into specified location

Upvotes: 1

Views: 2483

Answers (2)

Matias Masso
Matias Masso

Reputation: 1980

@ondrop event is useless here since it only reports the filename.
Blazor InputFile component triggers it's OnChange event when you drop a file on it's visible area.
The trick is to hide an InputFile component inside a drop area and spread it to fill the area completely.
The OnChange event handler receives a collection of IBrowseFile objects which can be read into MemoryStreams.
Further more, clicking on the drop area will open a file dialog the same way as if you had clicked on the InputFile.

<p>drop files on next area or click on it to select files:</p>

<div class="FileDrop">
    <InputFile multiple OnChange="FilesDropped"></InputFile>
</div>

@code {
    void FilesDropped(InputFileChangeEventArgs e)
    {
        foreach(var file in e.GetMultipleFiles())
        {
            Stream stream = file.OpenReadStream(maxAllowedSize: 100000000);
            // TO DO: do whatever you need with the file
            stream.Close();
        }
    }
}

Use next Css to spread and hide the InputFile inside the drop area. Note the use of ::deep pseudoelement to access the controls inside InputFile.

.FileDrop {
    cursor: pointer;
    display: block;
    width: 300px;
    height: 100px;
    border: 1px dashed black;
}
.FileDrop ::deep input[type=file] {
    width: 100%;
    height: 100%;
    opacity: 0;
}

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273274

You should use preventDefault here:

<div @ondrop:preventDefault="@OnDrop"></div>

and maybe you still have to handle Dragover as well, I'm not sure.

Upvotes: 1

Related Questions