Links for pdf files in server from static mvc web application - c#

I have few links to pdf files store in server in my static page. I would be able to click each link that would open a pdf file in browser. I referred to this link. But it is not working as I intended.
Here is my action method:
public ActionResult GetFileFromServer(string filename)
{
string folderpath = StrGlobal.file_folder.ToString();
string filepath = Path.Combine(folderpath, filename);
filepath = Path.GetfullPath(filepath);
return File(filepath, "application/pdf");
}
My view:
<p>
#Html.ActionLink(
linkText: "ABC Document",
actionName:"GetFileFromServer",
controllerName:"StaticPage",
routeValues:new {filename = "ABC.pdf"},
htmlAttributes:null
)
</p>
If I replace and hardcore filename in this line:
string filepath = Path.Combine(folderpath, "ABC.pdf");
It will open that specific pdf file. Otherwise I get an error saying
Value cannot be null. Parameter name: path2
Seems like value is not getting passed from view to controller. How do I fix this issue?

<a href="/staticpath/ABC.pdf" download>
Donloadpdf
</a>
Hi,
We can resolved issue by easy way with using html download functionality.

Related

Serve static pdf files in solution folder - in MVC pipeline , with different route

One of my old project we do have a static content file folder named XYZ which we are keeping in the same location fo the root.
Currently we are directly passing the url like 'siteaddress/XYZ/test.pdf' or siteaddress/XYZ/2020/Test1.pdf to get the pdf files.
Now we have a requirement to store some of the confidential files also in the path. So we are planning to restrict the direct access to the path and serve via MVC pipeline
we have added a handlers to enable the requests from the folder, to go through mvc pipeline
<add
name="ManagedPdfExtension"
path="XYZ/*/*.pdf"
verb="GET"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0"
/>
<add
name="ManagedPdfInnerFolderExtension"
path="CommonFiles/*/*.pdf"
verb="GET"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0"
/>
Also created a method to return the file in controller
[HttpGet]
[Route("XYZ/{attachmentName}")]
public ActionResult CommonFiles(string attachmentName)
{
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/XYZ/"+ attachmentName);
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
string fileName = "Test.pdf";
var cd = new ContentDisposition
{
Inline = true,
FileName = fileName
};
Response.Clear();
Response.AddHeader(CoreConstants.ContentDisposition, cd.ToString());
Response.AddHeader(CoreConstants.WindowTarget, CoreConstants.WindowTargetBlank);
Response.BufferOutput = false;
return File(fileBytes, "application/pdf");
}
This code works ok with files which are directly under folder XYZ
That means if I try a url like
siteaddress/XYZ/test.pdf which is working.
But for the pdf that are inside another folder, I am not able to get with the existing approach.
Since we have only single param attachmentName defined in the method i couldn't get the files under subfolders.
Is there any way to do the same in MVC ??
Because of some reasons, I cannot move all these items to database , change the folder structure . Also i cannot create a mapping table like
url : key and use the key instead.
Th urls are coming from a common table which is used in many applications. So changing that is bit difficult.
If the folder and subfolders are limited then may be with multiple route i could handle this. But here the subfolder number can be a variable too.
In fact from the following urls
siteadress/XYZ/abc/bn/test.pdf
siteadress/XYZ/abc/cf/bn/test.pdf
siteadress/XYZ/abc/bn/test.pdf
is there any way to make it hit a single controller method with a string params like
abc/bn/test.pdf
abc/cf/bn/test.pdf
abc/bn/test.pdf
??
Added a route with * in the property part.
[HttpGet]
[Route("CommonFiles/{*any}")]
public ActionResult CommonFiles(string attachmentName)
{
var filePathWithName = this.RouteData.Values["any"];
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/CommonFiles/"+ filePathWithName);
path = path.Replace("//", "/").Replace("/","//");
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
string fileName = "Test.pdf";
var cd = new ContentDisposition
{
Inline = true,
FileName = fileName
};
Response.Clear();
Response.AddHeader(CoreConstants.ContentDisposition, cd.ToString());
Response.AddHeader(CoreConstants.WindowTarget, CoreConstants.WindowTargetBlank);
Response.BufferOutput = false;
return File(fileBytes, "application/pdf");
}

How to use uploaded files from .net core API in my angular application?

I have trouble with display a image in my Angular app.
This is in my profile.ts and profile.html page
public createImgPath = (serverPath: string) => {
return `http://localhost:63040/${serverPath}`;
}
<img class="img-responsive" src="{{createImgPath(userApi.user.imageUrl.folderName)}}" />
From the server I get filepath:
var folderName = Path.Combine( "userImages", fileName);
return Ok(new { folderName });
When I try to display image in src I get the path but image is not display.
And I got error message:
It was very silly typo mistake. Instead "usersImages", in var folderName I used to use "userImages". I'm sorry for trouble to everyone.
I think you're supposed to return the file as a blob. Because you cannot send your images as a JSON to angular. Well, at first, change your backend code to something like this:
var folderName = Path.Combine( "userImages", fileName);
return new FileStream(folderName , FileMode.Open, FileAccess.Read);
and then change [HttpGet] to [HttpPost]
I don't know how to send your image file to the backend but I think you can fix your problem with these changes.

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.

how to upload a file to url

I'm trying to upload a file from browser and copy it to a URL folder
using c sharp.
( i have all the Permissions to this folder)
i have no problam upload the file to my hard drive
like this:
HttpPostedFileBase myfile;
var path = Path.Combine(Server.MapPath("~/txt"), fileName);
myfile.SaveAs(path);
i have try to upload it to URL like this but i am getting an exception
HttpPostedFileBase myfile;
var path =VirtualPathUtility.ToAbsolute("http://localhost:8080/game/images/"+fileName);
myfile.SaveAs(path);
the Exception:
System.ArgumentException: The relative virtual path 'http:/localhost:8080/game/images/ a baby bottle. Jpg' is not allowed here.
    In - System.Web.VirtualPath.Create (String virtualPath, VirtualPathOptions
You cannot upload the file to a remote location. If you want this to work you will have to modify the remote server so that it accepts file uploads, the same way your server accepts file uploads and then send an HTTP request to it using a WebClient. You cannot use the SaveAs method as it expects a local path.
You could have the following controller action:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase myFile)
{
if (myFile != null && myFile.ContentLength > 0)
{
var fileName = Path.GetFileName(myFile.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
myFile.SaveAs(path);
}
...
}
and a corresponding form with a file input:
#using (Html.BeginForm("Upload", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="myFile" />
<button type="submit">Click this to upload the file</button>
}
You should use Server.MapPath("Path")
var path = Server.MapPath("~/images/") + fileName);
myfile.SaveAs(path);

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