Show download progress in browser - c#

I'm working in a function to download pdfs from DropBox, I'm using ASP.net Core , everything works good. The only thing is that when you click in the download link it doesn't show any message and downloads the file. I would like to show the download progress like usually happens when we download something from Internet, I don't want any dialog to appear, just to show that the file was downloaded like normally happens in any browser like Chrome or IE and then have the choices 'Show in Folder' and things like that, what would I need to add?
public async Task DownloadPdf()
{
DropboxClient client2 = new DropboxClient("cU5M-a4exaAAAAAAAAABDVZsKdpPteNmwHslOeFEo-HByuOr4v4ONvXoAMCFyOXH");
string folder = "MyFolder";
string file = "Test PDF.pdf";
using (var response = await client2.Files.DownloadAsync("/" + folder + "/" + file))
{
using (var fileStream = System.IO.File.Create(#"C:\Users\User\Downloads\Test.pdf"))
{
(await response.GetContentAsStreamAsync()).CopyTo(fileStream);
}
}
}

I have a asp.net core project with an API that returns a file:
[HttpGet("{id}")]
public IActionResult Get(int id) {
byte[] fileContent = READ_YOUR_FILE();
FileContentResult result = new FileContentResult(fileContent, "application/octet-stream") {
FileDownloadName = id.ToString()
};
return result;
}
If I access in my browser the URL from this API (myapp/api/mycontroller/id), then I can see the file downloading.

Related

Downloading a document in PWA app ASP.NET MVC

Just curious about this and wanted to know about this matter.
I have downloaded a PWA app and set it to my ASP.NET MVC project.
In there I want to allow download a file and for that I have used this,
<a download href="#Url.Action("DownloadDoc","Ajax" ,new { id = item.Id})" target="_blank" class="btn-20 btn border-green-dark color-green-dark bi bi-arrow-down" />
The issue is it's not downloading, A new view will appear and the address bar shows the controller and the action, and the file Id, If I inspect this, in the network area I can see the file.
Normally when I used the same in HTML view, it opens up a new tab and then closes with downloading the file.
Here it won't work.
I want to know is there is another way of doing this ??
This is my controller code
public ActionResult DownloadDoc(int id) {
var q = from temp in db.CustomerScannedDocuments where temp.Id == id select temp.Attachment;
var type = from t in db.CustomerScannedDocuments where t.Id == id select t.File_Name;
string fileType = type.First().ToString();
string ext = Path.GetExtension(fileType);
byte[] cover = q.First();
if (cover != null) {
if (ext == ".pdf") {
return File(cover, "application/pdf");
} else {
return File(cover, "image/jpg");
}
} else {
return null;
}
}
I want to know is there is another way of doing this ?
There are couple of ways you could achieve your requirement. You could try in following ways:
Way: 1
Controller:
public async Task<IActionResult> DownloadImage(string imageName)
{
var path = Path.GetFullPath("./wwwroot/ImageName/Cover/" + imageName);
MemoryStream memory = new MemoryStream();
using (FileStream stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, "image/png", Path.GetFileName(path));
}
Download Link HTML:
<a asp-controller="Application" asp-action="DownloadImage" class="btn btn-info" asp-route-imageName="#item.ImageName">Download</a>
Output:
Note: It doesn't require any Nuget package
Way: 2 When you want to display PDF on your browser from database Model
Solution:
public ActionResult DisplayPdfOnBrowserFromDatabaseList()
{
var data = _context.Members.ToList();
var pdf = data.ToPdf();
MemoryStream ms = new MemoryStream(pdf);
return new FileStreamResult(ms, "application/pdf");
}
Note: To handle this scenario you need to use 3rd party Nuget package which is ArrayToPdf You can search on Nuget package on your visual studio. You can also check the GitHub Link. Finally need to add using ArrayToPdf; on top.
Output:
Way: 3 When you want to download PDF on your browser from database model or existing file
Solution:
public ActionResult DownloadPDFOnBrowser()
{
var data = _context.Members.ToList();
var byteArray = data.ToPdf();
MemoryStream stream = new MemoryStream(byteArray);
string mimeType = "application/pdf";
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = "DatabaseListToPdf.pdf"
};
}
Note: As described above we need to add using ArrayToPdf; on top. To handle this scenario you need to use 3rd party Nuget package which is ArrayToPdf You can search on Nuget package on your visual studio. See the screenshot below:

Angular 5 - uploads disappear after publishing new version

In an angular 5 app with a .net core backend, a user can upload attachments for his/her projects. The attachments are being send to the .NET Core backend and are saved inside the WebRootPath in a folder with the name of the project code.
[HttpPost]
[Route("api/projects/{id}/upload")]
[Consumes("application/json", "application/json-patch+json", "multipart/form-data")]
public async Task<IActionResult> UploadAttachment(int id, FileForUpload upload)
{
var project = await _orbaAgent.GetDefaultProject(id);
if (upload != null && upload.File != null && upload.File.Length > 0)
{
var file = upload.File;
string serverPath = string.IsNullOrEmpty(_hostingEnvironment.WebRootPath) ? _hostingEnvironment.ContentRootPath : _hostingEnvironment.WebRootPath;
serverPath = Path.Combine(serverPath, "attachments", project.Code);
if (!Directory.Exists(serverPath))
{
Directory.CreateDirectory(serverPath);
}
using (var fileStream = new FileStream(Path.Combine(serverPath, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
return Ok();
}
The location of the attachments becomes 'app/attachments/'projectcode'/.
To download the files, I use an anchor element on the html page
<a href="attachments/{{defaultProject.code}}/{{att.name}}" download>{{att.name}}</a>
Uploading/downloading works perfect.
The only problem is that when I deploy a new version of the application, the app/attachment folder dissapears and so do all of the attachments.
Is there any way to prevent the deletion of this folder for new versions? Or if this is not possible, should I save the files somewhere else?

How to get the URL of Dropbox uploaded image in ASP.NET

I have written a small method that uploads files on Dropbox and that method is working absolutely fine but the issue is how can I get the URL of the uploaded image so that I hit that URL on browser and it shows me the image.
Here is the code of uploading files:
public static async Task Run()
{
var accessToken = ConfigurationManager.AppSettings["DropBoxAccessToken"];
using (var dbx = new DropboxClient(accessToken))
{
//var full = await dbx.Users.GetCurrentAccountAsync();
await Upload(dbx, "/Test", "Test Image.jpg");
}
}
static async Task Upload(DropboxClient dbx, string folder, string file)
{
var readContent = System.IO.File.ReadAllBytes(#"D:\Images\IMG_20161127_204200968.jpg");
using (var mem = new MemoryStream(readContent))
{
var updated = await dbx.Files.UploadAsync(
folder + "/" + file,
WriteMode.Overwrite.Instance,
body: mem);
var mediaInfo = updated.MediaInfo;
}
}
I have tried to get details of uploaded image by hovering on var updated but didn't get the URL.
Any help?
To get a link to a file via the Dropbox API, you have two options:
GetTemporaryLinkAsync: this returns a temporary link, but isn't meant for being displayed in the browser directly.
CreateSharedLinkWithSettingsAsync: this returns a shared link that points to a preview page for the file that can be displayed in the browser.

Download File through headers from different server

I have PDF file placed on different (FILE-Server) server machine, and the IIS machine on which my MVC application is hosted have rights to that File-Server. From IIS machine i can access the file through following URI:
file://file-server/data-folder/pdf/19450205.pdf
I want to enable my MVC app's users to download their respective files by clicking on download link or button. So probably i would have to write some Action for that link/button.
I tried to use File return type for my Action method in following way:
public ActionResult FileDownload()
{
string filePth = #"file://file-server/data-folder/pdf/19450205.pdf";
return File(filePth , "application/pdf");
}
but the above code gives exception of URI not supported.
I also tried to use FileStream to read bytes inside array return that bytes towards download, but FileStream also gives error of not proper "Virtual Path" as the file is not placed inside virtual path, its on separate server.
public ActionResult Download()
{
var document = = #"file://file-server/data-folder/pdf/19450205.pdf";
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = document.FileName,
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(document.Data, document.ContentType);
}
Thanks for the replies, but both suggestion did not work.
as file needs to be accessed over URI, using FileInfo gives error: URI formats are not supported.
I managed to get this done through following mechanism:
public ActionResult FaxFileDownload()
{
string filePth = #"file://file-server/data-folder/pdf/19450205.pdf";
WebClient wc = new WebClient();
Stream s = wc.OpenRead(filePth);
return File(s, "application/pdf");
}
Thanks to All.

Open external PDF file in asp.net MVC 2

I know how to open an internal pdf file :
public ActionResult GetPDF( string filename )
{
return File( filename, "application/pdf", Server.HtmlEncode( filename ) );
}
question is, how to open a PDF file from an other/external website, e.g. http://example.com/mypdffile.pdf
You don't really need a controller action to do this. You could simply:
Open mypdffile.pdf
Of course if you want to hide this address from the user you could use a WebClient to fetch it on the server:
public ActionResult GetPDF()
{
using (var client = new WebClient())
{
var buffer = client.DownloadData("http://www.blabla.com/mypdffile.pdf");
return File(buffer, "application/pdf", "mypdffile.pdf");
}
}
And in your view:
<%= Html.ActionLink("Download PDF", "GetPDF") %>
You will need it locally anyway to do any processing so, you can download it to local folder and then show it. use WebClient or HttpRequest/HttpResponse objects to do the downloading

Categories

Resources