Error While trying to view PDF document in browser it just get downloaded [ASP.net Core 3.0] - asp.net-core

I have tried to view pdf documents in my ASP.net core application but when I clicked on Read button the pdf document just get downloaded
Here is My Code
In my Home Controller I have GetPdf Action
public ActionResult GetPdf(string fileName)
{
string filePath = "~/file/" + fileName;
Response.Headers.Add("Content-Disposition", "inline; filename=" + fileName);
return File(filePath, "application/pdf");
}
and in the View part I have used
Read

Turn off any download manager software installed on your system. When you try to read the pdf the download manager will take it over to download it.

Change your ActionMethod to this -
public ActionResult GetPdf(string fileName)
{
string filePath = "~/file/" + fileName;
Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
return File(filePath, "application/pdf");
}
Note the change of Response.Headers.Add to Response.AddHeader

Related

non-invocable member 'File' cannot be used like a method error message- what am I missing?

I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?
This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.

JSF PDF not downloadable while returned from Servlet [duplicate]

This question already has an answer here:
Internet Explorer 9 does not use file name for inline attachments
(1 answer)
Closed 3 years ago.
I have a form that once completed opens a new tab and calls my bean method annonceReturn().
This method sends back a pdf file. The problem is that as I open a new tab with _blank, the URL ends with .xhtml. Even the filename is displayed as being in my exemple "list.xhtml" (the last part of the URL). The problem is that I can't download this file because it's not considerated as a pdf file.
This is my xhtml file :
<h:form id="form">
<p:commandButton id="envoiRetour" onclick="this.form.target = '_blank';"
actionListener="#{returnCtrl.announceReturn()}"
value="Open PDF in new tab"
ajax="false" />
</h:form>
This is the returnCtrl.annonceReturn() method :
public void announceReturn() throws MalformedURLException, FileNotFoundException, DocumentException, BadElementException, IOException, InterruptedException {
String referenceAnnouncement = "C:/Users/path_to_my_pdf_file.pdf";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(referenceAnnouncement), 10240);
response.reset();
response.setHeader("Content-type", "application/pdf");
response.setContentLength((int)new File(referenceAnnouncement).length());
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Content-disposition", "inline; filename=" + "file.pdf");
response.setHeader("pragma", "public");
output = new BufferedOutputStream(response.getOutputStream(), 10240);
byte[] buffer = new byte[10240];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
} finally {
output.close();
input.close();
}
}
How can I do to open this PDF in a new tab and be able to download it ?
When I try to download it, it says there is a network error (and it tries to save it as xhtml file).
EDIT : this is the question that helped me : How to open a PDF file in a new tab
EDIT 2 : the problem is not that the PDF doesn't show. The problem is that it shows in the new tab but when I try to download it, the explorer wants to save it as an XHTML file.
EDIT 3 : as mentionned here -> Open PDF in new tab, saving file gives wrong file name
it seems the filename is ignored if the disposition is not "attachment"... So I think I need to think about another way to do it.
Thanks for your time.
Try 'attachment' instead of 'inline' to force the browser saving the file (instead of trying to open with the associated plugin - if installed)
response.setHeader("Content-disposition", "attachment; filename=" + "file.pdf");
Hope it helps.
Beppe
Here is my code, hope it helps.
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
File temp = File("./path/abc.pdf");
temp.deleteOnExit();
ec.responseReset();
ec.setResponseContentType("application/pdf");
ec.setResponseContentLength((int)temp.length());
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + temp.getName() + "\""); //inline;
OutputStream output = ec.getResponseOutputStream();
Files.copy(temp.toPath(), output);
fc.responseComplete();
I have tested in my project, here is the solution:
1 - Create button
<h:commandButton
onclick="this.form.target='_blank'"
id="cmdOpenPDF"
action="#{bean.openPDF(bean.code)}"
value="New PDF">
</h:commandButton>
2 - The bean has a function with a redirect link to PDF. This sample the pdf in the root folder.
public void openPDF(String code) throws Exception {
String filePdfName ="";
try {
//Make sure that this file in root
File pdf = new File("sample.pdf");
filePdfName = pdf.getName();
} catch (Exception ex) {
ex.printStackTrace();
}
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/" + filePdfName);
}

Rename azure blob file and Download it

I have few files in azure blobs that are stored with unique file names and when the client wants to download, i want to rename to a friendly name.
I'm still using 2014 azure storage dlls in my project and i'm not planning to update them anytime soon. So i can't use built-in ContentDeposition and rename it.
I tried using following code in my controller:
var blob = blobStorage.GetBlobRef("https://mysite.blob.core.windows.net/my-container/WERF3234435FFF_ERFas23E.doc");
MemoryStream memStream = new MemoryStream();
blob.DownloadToStream(memStream);
Response.ContentType = blob.Properties.ContentType;
Response.AddHeader("Content-Disposition", "Attachment; filename=abcd_New.doc");
Response.AddHeader("Content-Length", blob.Properties.Length.ToString());
Response.BinaryWrite(memStream.ToArray());
but its not downloading the file.
I also tried using this:
MemoryStream memStream = new MemoryStream();
blob.DownloadToStream(memStream);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = blob.Properties.ContentType;
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment; filename=" + friendlyName.doc);
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", blob.Properties.Length.ToString());
System.Web.HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
System.Web.HttpContext.Current.Response.End();
I have my business logic in a separate solution and getting the blob reference from there to my main solution.
Am i missing something?
When we're talking about ASP.NET MVC, I'm missing the Controller/Action in your code? You're not supposed to write to the HttpContext yourself when doing ASP.NET MVC. You have ActionResults for that.
public ActionResult Download()
{
// ...
var bytes = memStream.ToArray();
return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, "abcd_New.doc");
}
The browser will decide whether to open the file download or open it directly within the browser window. If you want to control that, you will need the following piece of code before you call the return File(... method:
var contentDisposition = new System.Net.Mime.ContentDisposition
{
FileName = "abcd_New.doc",
Inline = false // true will try to open in Browser, false will download
};
Response.AppendHeader("Content-Disposition", contentDisposition.ToString());
We need to flush our response after wrote a file to response. I use the code which you provided. After adding following code, I can see the file can be download from server.
Response.BinaryWrite(memStream.ToArray());
Response.Flush();
Response.End();

I can't extract files in program files folder

I'm working on custom action and wix.The files are not extracting in program files (x86) folder.But the files are extracting correctly other than program files (x86). I have written code using .NET FRAMEWORK 4.0.
namespace Installer
{
public class CustomActions
{
[CustomAction]
public static ActionResult CustomAction1(Session session)
{
session.Log("Begin Extracting");
string FinalPath = session["APPDIR"];``
string zPath = #"C:\Users\AppData\Local\Temp\Install\7za.exe";
string ExtractPath = #"C:\Program Files (x86)\Samples\";
string sourcePath = #"C:\Program Files (x86)\Samples\source.zip";
try`
{
ProcessStartInfo pro = new ProcessStartInfo();``
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + sourcePath + "\" -o" + ExtractPath;
Process x = Process.Start(pro);
x.WaitForExit();
}
catch (System.Exception Ex)
{
}
return ActionResult.Success;
}
}
}
First of all you need to debug it properly. You're throwing away any error that might be thrown. Sorry to say this, but your question is unfortunately more like "how can I find out why my code is not working when I've thrown away any exceptions it might raise?"
There's no guarantee that the zip extension will work correctly just by starting it. It might work if WinZip is installed, but not if all that happens is that Explorer opens to look at the files.
You should use the classes that will unzip it. Example here:
https://msdn.microsoft.com/en-us/library/ms404280(v=vs.110).aspx

How do I open a file when clicking an ActionLink?

How do I open an existing file on the server when a user clicks an actionlink? The following code works for downloading a file but I want to open a new browser window, or tab, and display the file contents.
public ActionResult Download()
{
return File(#"~\Files\output.txt", "application/text", "blahblahblah.txt");
}
You must add "inline" for a new tab.
byte[] fileBytes = System.IO.File.ReadAllBytes(contentDetailInfo.ContentFilePath);
Response.AppendHeader("Content-Disposition", "inline; filename=" + contentDetailInfo.ContentFileName);
return File(fileBytes, contentDetailInfo.ContentFileMimeType);
The way you're using the File() method is to specify a file name in the third argument, which results in a content-disposition header being sent to the client. This header is what tells a web browser that the response is a file to be saved (and suggests a name to save it). A browser can override this behavior, but that's not controllable from the server.
One thing you can try is to not specify a file name:
return File(#"~\Files\output.txt", "application/text");
The response is still a file, and ultimately it's still up to the browser what to do with it. (Again, not controllable from the server.) Technically there's no such thing as a "file" in HTTP, it's just headers and content in the response. By omitting a suggested file name, the framework in this case may omit the content-disposition header, which is your desired outcome. It's worth testing the result in your browser to see if the header is actually omitted.
Use a target of blank on your link to open it in a new window or tab:
Download File
However, forcing the browser to display the contents is out of your control, as it entirely depends on how the user has configured their browser to deal with files that are application/text.
If you are dealing with text, you can create a view and populate the text on that view, which is then returned to the user as a regular HTML page.
please try this and replace your controller name and action name in html action link
public ActionResult ShowFileInNewTab()
{
using (var client = new WebClient()) //this is to open new webclient with specifice file
{
var buffer = client.DownloadData("~\Files\output.txt");
return File(buffer, "application/text");
}
}
OR
public ActionResult ShowFileInNewTab()
{
var buffer = "~\Files\output.txt"; //bytes form this
return File(buffer, "application/text");
}
this is action link which show in new blank tab
<%=Html.ActionLink("Open File in New Tab", "ShowFileInNewTab","ControllerName", new { target = "_blank" })%>
I canĀ“t vote your answered as is useful, follow dow. Thanks very much !
public FileResult Downloads(string file)
{
string diretorio = Server.MapPath("~/Docs");
var ext = ".pdf";
file = file + extensao;
var arquivo = Path.Combine(diretorio, file);
var contentType = "application/pdf";
using (var client = new WebClient())
{
var buffer = client.DownloadData(arquivo);
return File(buffer, contentType);
}
}