Home > database >  Direct download of the audio file(web url) without playing in the browser in asp.net core
Direct download of the audio file(web url) without playing in the browser in asp.net core

Time:09-05

I want to have a link on the page (asp.net 5) that points to an audio file on the web, actually on my download site. Now when the link is clicked, it starts playing in a new window, which I don't want. But I want to start downloading. I also use the download tag, but it doesn't work. Maybe it is because the link is outside the domain of the site. If I use the following codes, the file will be downloaded, but the problem here is that nothing will be displayed to the user until the end of the download, and after the end of the download, the downloaded file will be seen at once, and this may mislead the user. In fact, I want the download to start normally and the user to see the download process.

var net = new System.Net.WebClient();
            var data = net.DownloadData("https://myDownloadSite/file.mp3");
            var content = new System.IO.MemoryStream(data);
            var contentType = "APPLICATION/octet-stream";
            var fileName = "file.mp3";
            return File(content, contentType, fileName);

CodePudding user response:

You can directly download by using anchorTag

<a href="https://myDownloadSite/file.mp3" download>
  Download
</a>

Or you can use below code for return file in .net core

public async Task<IActionResult> Download() 
{
        Stream stream = await {{__get_stream_based__}}

        if(stream == null)
            return NotFound(); // returns a NotFoundResult with Status404NotFound response.

        return File(stream, "application/octet-stream"); // returns a FileStreamResult
}  

enter image description here

enter image description here

Second:

If you still can't pop up the download prompt box after changing the transfer rate, you can use JavaScript to call it:

<script>
    window.open('/Home/Index', 'DownloadWindowName');
</script>

Third:

You can also refer to Abdul Saleem's answer to add a progress bar.

Hope this can help you, good luck.

  • Related