Download Files using File Upload

With the File Upload component, I display a list of preloaded files. I would like to be able to click on file/row to call a method to download the file. I don't see a File Upload event that executes on click passing the FileInfo argument.

4 Replies 1 reply marked as answer

BC Berly Christopher Syncfusion Team March 3, 2021 04:44 PM UTC

Hi George, 
  
Greetings from Syncfusion support. 
  
We have achieved the requested requirement with help of template concept. Kindly refer the below code example. 
  
[index.razor] 
@using Syncfusion.Blazor.Inputs 
@using System.IO 
 
 
<SfUploader ID="UploadFiles"> 
    <UploaderTemplates> 
        <Template> 
            <span class='name file-name'>@(context.Name)</span> 
            <span class='file-size'>@(context.Size) bytes</span> 
            <span class="upload-status">@(context.Status)</span> 
            <span class="fa fa-download" title="Download" @onclick="@(e => OnClick(e, context.Name))"></span> 
        </Template> 
    </UploaderTemplates> 
    <UploaderFiles> 
        <UploaderUploadedFiles Name="Nature" Size=500000 Type=".png"></UploaderUploadedFiles> 
        <UploaderUploadedFiles Name="TypeScript Succinctly" Size=12000 Type=".pdf"></UploaderUploadedFiles> 
        <UploaderUploadedFiles Name="ASP.NET Webhooks" Size=500000 Type=".docx"></UploaderUploadedFiles> 
    </UploaderFiles> 
    <UploaderEvents ValueChange="OnChange" OnRemove="onRemove"></UploaderEvents> 
</SfUploader> 
 
@code { 
 
    SfUploader uploaderObj; 
    [Inject] 
    protected IJSRuntime JsRuntime { get; set; } 
 
    List<UploaderUploadedFiles> file = new List<UploaderUploadedFiles>(); 
 
 
    private void OnChange(UploadChangeEventArgs args) 
    { 
        foreach (var file in args.Files) 
        { 
            var path = @"path" + file.FileInfo.Name; 
            FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.Write); 
            file.Stream.WriteTo(filestream); 
            filestream.Close(); 
            file.Stream.Close(); 
        } 
    } 
    private void onRemove(RemovingEventArgs args) 
    { 
        foreach (var removeFile in args.FilesData) 
        { 
            if (File.Exists(Path.Combine(@"rootPath", removeFile.Name))) 
            { 
                File.Delete(Path.Combine(@"rootPath", removeFile.Name)); 
            } 
        } 
    } 
    public async Task OnClick(MouseEventArgs e, string filename) 
    { 
        await JsRuntime.InvokeVoidAsync("onUpload", "UploadFiles", filename); 
    } 
} 
[wwwroot/upload.js] 
window.onUpload = (id, filename) => {  
    let url = "https://localhost:44394/api/SampleData/Download?filename=" + filename;  
    window.location.rel='nofollow' href = url;  
}; 
[Data/SampleData/Download] 
  [HttpGet("[action]")] 
        public FileResult Download(string filename) 
        { 
 
            var filePath = Path.Combine( 
                      Directory.GetCurrentDirectory()); 
            IFileProvider provider = new PhysicalFileProvider(filePath); 
            IFileInfo fileInfo = provider.GetFileInfo(filename); 
            var readStream = fileInfo.CreateReadStream(); 
            var mimeType = "application/pdf"; 
            return File(readStream, mimeType, filename); 
        } 
 
  
  
Regards, 
Berly B.C 


Marked as answer

GF George Franklin March 4, 2021 09:13 PM UTC

Thanks


ÀL À la mode Clothing Outlet replied to Berly Christopher November 25, 2024 10:24 PM UTC

Hi. I have a similar situation, although I want to use the multi-format-viewer demo in my project. I have a section that shows a preloaded document:

Image_8104_1732573183542

Of which when I press "View License" i have a pop up dialog on which I wish to display the license. How do I download or read this preloaded file from my desktop?


<!--License Upload-->

<RadzenRow>

    <RadzenFormField Text="License Uploader" Style="background-color:#ebeef1;width: 100%;">

        <ChildContent>

            <SfUploader ID="UploadFiles" @ref="UploadObj" ShowProgressBar="true" AutoUpload="true"

            AllowMultiple="false" CssClass="e-primary">

                <UploaderButtons Browse="Select Driver's License"></UploaderButtons>

                <UploaderEvents BeforeUpload="BeforeUpload" OnActionComplete="OnCom" Success="OnSuccess" ValueChange="OnChange"></UploaderEvents>

                @if (driver.UploadedLicense)

                {

                    <UploaderFiles>

                        <UploaderUploadedFiles Name="@driver.LicenseFile.Name" Size="@driver.LicenseFile.Size" Type="@driver.LicenseFile.Format"></UploaderUploadedFiles>

                    </UploaderFiles>

                }

            </SfUploader>

        </ChildContent>

        <Helper>

            <RadzenText TextStyle="TextStyle.Caption">* Document will be saved with as '@driver.Id'</RadzenText>

        </Helper>

    </RadzenFormField>

</RadzenRow>

@if (driver.UploadedLicense)

{

    <!-- View Doc -->

    <RadzenButton Click="@((args) => {LicenseDialogVisibility = true; ViewLicenseFile();})" Variant="Radzen.Variant.Filled" Shade="Shade.Dark" Icon="view" Text="View License" ButtonStyle="ButtonStyle.Dark" />

}



<!--View License dialog-->

<SfDialog Width="683px" Height="100%" ShowCloseIcon="false" IsModal="true" CloseOnEscape="true"

@bind-Visible="@LicenseDialogVisibility">

    <DialogTemplates>

        <Content>

            <RadzenStack Style="height: 100%;">

                <!-- View Doc -->

                <SfPdfViewer2 @ref="viewer" ID="pdfviewer" Height="100%" Width="100%">

                    <PdfViewerToolbarSettings ToolbarItems="@ToolbarItems"></PdfViewerToolbarSettings>

                </SfPdfViewer2>

                <!--Close-->

                <RadzenButton Click="@((args) => LicenseDialogVisibility = false)" Variant="Radzen.Variant.Filled" Shade="Shade.Dark" Icon="close" Text="Close" ButtonStyle="ButtonStyle.Dark" />

            </RadzenStack>

        </Content>

    </DialogTemplates>

</SfDialog>



YS Yohapuja Selvakumaran Syncfusion Team November 29, 2024 12:14 PM UTC

Hi  George Franklin,


Based on the information provided, it appears that you are looking to facilitate file downloads using the Syncfusion Blazor File Upload component. The File Upload component is primarily designed for uploading files. However, you can incorporate a download button within the file list using the Template feature, which allows users to download files from the server based on the file name. Please refer to the below shared code snippet and sample for more information.

[Razor]

 

@using Syncfusion.Blazor.Inputs

@using System.IO

@inject HttpClient Http

 

<h3>Syncfusion Blazor File Upload - Demo of File Upload and Download</h3>

<SfUploader ID="UploadFiles" @ref="UploaderObj">

   <UploaderAsyncSettings SaveUrl="api/SampleData/Save" RemoveUrl="api/SampleData/Remove"></UploaderAsyncSettings>

   <UploaderTemplates>

       <Template>

           <ul class="e-upload-files">

               <li class="e-upload-file-list e-upload-success" data-file-name="Sample1.jpg" data-files-count="1">

                   <span class="e-file-container">

                       <span class="e-file-name" title="@(context.Name)">@(context.Name)</span>

                       <span class="e-file-type">@(context.Type)</span>

                       <span class="e-file-size">@(context.Size) bytes</span>

                       <span class="e-file-status">@(context.Status)</span>

                   </span>

                   <span class="e-icons e-file-delete-btn" tabindex="0" title="Delete file" aria-label="Delete file" role="button" @onclick="@(e => DeleteFile(context))"></span>

                   <span class="e-file-status">

                       Click To Download the File

                       <a class="e-icons e-download e-btn" title="Download" rel='nofollow' href="@($"https://localhost:7066/api/SampleData/Download?filename={context.Name}")" download></a>

                   </span>

               </li>

           </ul>

       </Template>

   </UploaderTemplates>

   <UploaderEvents BeforeRemove="@BeforeRemovehandler"></UploaderEvents>

</SfUploader>

 

@code {

 

   public SfUploader UploaderObj { get; set; }

 

   public void BeforeRemovehandler(BeforeRemoveEventArgs args)

   {

       args.PostRawFile = false;

   }

 

   public async Task DeleteFile(Syncfusion.Blazor.Inputs.FileInfo fileData)

   {

       await UploaderObj.RemoveAsync(new Syncfusion.Blazor.Inputs.FileInfo[] { fileData });

   }

}

 

[Controller]

       [HttpPost("[action]")]

       public void Remove(string UploadFiles) // Delete the uploaded file here

       {

           if (UploadFiles != null)

           {

               var filePath = Path.Combine(uploads, UploadFiles);

               if (System.IO.File.Exists(filePath))

               {

                   //Delete the file from server

                    System.IO.File.Delete(filePath);

               }

           }

       }

 

       [HttpGet("[action]")]

       public FileResult Download(string filename)

       {

           var filePath = Path.Combine(Directory.GetCurrentDirectory() + "\\Uploaded Files");

           IFileProvider provider = new PhysicalFileProvider(filePath);

           IFileInfo fileInfo = provider.GetFileInfo(filename);

           var readStream = fileInfo.CreateReadStream();

           var mimeType = "application/pdf";

           return File(readStream, mimeType, filename);

       }

 

Code Explanation:

  • The UploaderTemplates section uses a custom template to display the uploaded files.
  • A download button is added within the file list, which triggers the file download from the server.
  • The DeleteFile method handles the deletion of uploaded files.
  • The Remove action deletes files from the server.
  • The Download action returns the file as a FileResult for downloading.

Note:

  • The file download functionality is separate from the file upload component. The download method is a standalone function and is not a built-in feature of the Syncfusion File Uploader.
  • You can customize the Download method according to your specific requirements. The current implementation is a basic example to demonstrate the functionality.
  • Ensure that the file path in the Download method correctly points to the directory where the uploaded files are stored.

 

Samplehttps://www.syncfusion.com/downloads/support/directtrac/general/ze/Blazor-Upload-And-Download796410024


Regards,

Yohapuja S



Loader.
Up arrow icon