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.
Related
I'm developing a website with ASP.NET MVC 5 + Web API. One of the requirements is that users must be able to download a large zip file, which is created on the fly.
Because I immediately want to show progress of the user, my idea was to use a PushStreamContent with a callback in the resonse. The callback creates the zipfile and streams it to the response.
When I implement this as follows, starting from an empty ASP.NET MVC + Web API project, it works as expected. As soon as the result is returned to the client, the callback gets invoked and
the zipfile is streamed to the client. So the user can see progress as soon as the callback creates the zip archive and add files to it.
[RoutePrefix("api/download")]
public class DownloadController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
var files = new DirectoryInfo(#"c:\tempinput").GetFiles();
var pushStreamContent = new PushStreamContent(async (outputStream, httpContext, transportContext) =>
{
using (var zipOutputStream = new ZipOutputStream(outputStream))
{
zipOutputStream.CompressionLevel = CompressionLevel.BestCompression;
foreach (var file in files)
{
zipOutputStream.PutNextEntry(file.Name);
using (var stream = File.OpenRead(file.FullName))
{
await stream.CopyToAsync(zipOutputStream);
}
}
}
});
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = pushStreamContent
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment") {FileName = "MyZipfile.zip"};
return response;
}
}
Now, I have to integrate this in an existing website, which is configured to use Microsoft.Owin.OwinMiddleware. I used the same code as pasted above, but now the behavior is different: during the creation of the zipfile, it 's not streamed to the response, but only downloaded when the creation of the zip has finished. So the user doesn't see any progress during the creation of the file.
I also tried a different approach in my Web API + Owin project, as described here: (generate a Zip file from azure blob storage files).
In an empty Asp.NET MVC project (without OWIN middleware), this works exactly as expected, but when OWIN is involved, I get this HTTPException and stacktrace:
System.Web.HttpException: 'Server cannot set status after HTTP headers have been sent.'
System.Web.dll!System.Web.HttpResponse.StatusCode.set(int value) Unknown
System.Web.dll!System.Web.HttpResponseWrapper.StatusCode.set(int value) Unknown
Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.OwinCallContext.Microsoft.Owin.Host.SystemWeb.CallEnvironment.AspNetDictionary.IPropertySource.SetResponseStatusCode(int value) Unknown
It seems that OWIN wants to set a response status, although that was already done in my Get() method (HttpResponseMessage(HttpStatusCode.OK)).
Any suggestions how to fix this or ideas for a different approach?
Thanks a lot!
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.
User uses my browser based on CefSharp. He uploads a file (which is selected in file input HTML control) to known server using XMLHttpRequest (it's JavaScript object for AJAX requests). I want to intercept and to read the uploading file in my browser.
I do the same in my browser based on Awesomium using IResourceInterceptor. It's easy, because ResourceRequest parameter contains full local path of the file. How can I do the same in CefSharp browser?
How user uploads file using XMLHttpRequest (JavaScript):
var file = document.getElementById('fileInput').files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.open('POST', '/upload', true);
xhr.send(formData);
Awesomium way to intercept user's file (C#):
class MyResourceInterceptor : IResourceInterceptor
{
public ResourceResponse OnRequest(ResourceRequest request)
{
// intercept URL with /upload path only
if (request.Url.AbsolutePath != "/upload")
{
return null;
}
// full local path for user's file
var filePath = request[1].FilePath;
// now I can read and process the file
}
public bool OnFilterNavigation(NavigationRequest request)
{
return false;
}
}
CefSharp doesn't currently expose a way to access Post Data which is what I'm guessing you require.
I have implemented a PR that contains a basic implementation, feel free to test it out. See https://github.com/cefsharp/CefSharp/pull/1113
The other option you have is implement OnFileDialog, you'd have to display your own dialog, simple enough though.
https://github.com/cefsharp/CefSharp/blob/cefsharp/41/CefSharp/IDialogHandler.cs#L38
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
How can i download file from other server and save it at my own using mvc asp.net with c#?
I am only able to read your title, nevertheless:
WebClient client = new WebClient();
client.DownloadFile("http://your-address.com/FileToDonwload.ext", "c:\PathToTheFileToCreate");
should do what you wanted.
i'd use the System.Web.Mvc.FilePathResult along the following lines:
// most controller logic ommitted
public ActionResult DownloadFile(int fileID)
{
// in this example fileID would map to a file location in the database
var item = _repository.GetByKey(fileID);
// item.DocType would equal "application/msword" / "image/jpeg" etc, etc;
return File(item.DocumentLocation, item.DocType);
}
[edit] - ooops, just realised that this will only work on same server/domain, but have left for reference