I want to let user to download a file from server.
I looked up for the solution and when trying to make an example - ended up with this:
#Route("test-download")
public class Download extends VerticalLayout {
public Download() {
Anchor downloadLink = new Anchor(createResource(), "Download");
downloadLink.getElement().setAttribute("download", true);
add(downloadLink);
}
private AbstractStreamResource createResource() {
return new StreamResource("/home/johny/my/important-file.log", this::createExportr);
}
private InputStream createExportr(){
return null;
}
}
Which is giving java.lang.IllegalArgumentException: Resource file name parameter contains '/' when I go to the page in browser.
How do I make a download button (or anchor) knowing file location on disk?
Have a look at the documentation, paragraph "Using StreamResource". The first parameter is just a file name that will be used by the browser to propose that file name to the user when downloading. So you could pass it like "important-file.log". The content of the download is provided by the InputStream parameter. For instance, you could read from your file, see here:
File initialFile = new File("src/main/resources/sample.txt");
InputStream targetStream = new FileInputStream(initialFile);
Related
I want to render or download a URL that links to a PDF in a Grails controller method. I'm okay with either opening this is in a new or the same tab, or just downloading it. How is this done in grails?
So far I have:
render(url: "http://test.com/my.pdf")
However, I get errors with this and other ways I've tried, such as rendering a response with content. Any clues?
Yes you can absolutely do it easily:
First get the file from the URL (if you don't have a local file) for example:
class FooService {
File getFileFromURL(String url, String filename) {
String tempPath = "./temp" // make sure this directory exists
File file = new File(tempPath + "/" + filename)
FileOutputStream fos = new FileOutputStream(file)
fos.write(new URL(url).getBytes())
fos.close()
file.deleteOnExit()
return file
}
}
Now in your controller, do this to allow user to automatically download your PDF file:
class FooController {
def fooService
def download() {
String filename = "my.pdf"
// You can skip this if you already have that file in the same server
File file = fooService.getFileFromURL("http://test.com/my.pdf", filename)
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "${params.contentDisposition}; filename=${filename}")
response.outputStream << file.readBytes()
return
}
}
Now as the user will hit /foo/download the file will be dowloaded automatically.
One option is
class ExampleController {
def download() {
redirect(url: "http://www.pdf995.com/samples/pdf.pdf")
}
}
Going to localhost:8080/appName/example/download will, depending on the users browser preferences, either download the file or open the file in the same tab for reading.
I works with grails 2.5.0
I'm using MvcRazorToPdf in a Azure website and create my PDF's and output them in the browser.
Now i'm creating a new function to directly email the PDF as attachment (without output them in the browser).
Does anybody know if it is possible to save the PDF (with MvcRazorToPdf) as a MemoryStream or Byte[]?
I think you can handle this in ResultFilter, I used below code to allow user to download file and prompt for download popup, in this way you can grab all your memory stream and store somewhere to send email afterwords.
public class ActionDownloadAttribute : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + "Report.pdf");
base.OnResultExecuted(filterContext);
}
}
[ActionDownload]
public ActionResult GeneratePdf()
{
List<Comment> comments = null;
using (var db = new CandidateEntities())
{
comments = db.Comments.ToList();
}
return new PdfActionResult("GeneratePdf", comments);
}
I have implemented something like that. So basically I have not been changing my method to output PDF. What I have done is used restsharp to make request at URL where I get PDF then what you have is in lines of (this is partial code only so you can get idea )
var client = new RestClient(IAPIurl);
var request = new RestRequest(String.Format(IAPIurl_generatePDF, targetID), Method.GET);
RestResponse response = (RestResponse) client.Execute(request);
// Here is your byte array
response.RawBytes
Otherwise you can use my answer from here where I discussed directly returning a file.
Hope this helps!
can you tell me a hint to start an Epub reader app for blackberry?
I want the simplest way to do it, is there any browser or UI component that can read & display it?
I want to download it from a server then view it to the user to read it.
couple of days ago, an Epub reader library was added here, I tried to use it, but it has some difficulties, it could open Epubs only from resources, but not from file system, so I decided to download the source and do some adaptation.
First, I wrote a small function that opens the Epub file as a stream:
public static InputStream GetFileAsStream(String fName) {
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector
.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
} catch (IOException e) {
System.out.println(e.getMessage());
return is;
Then, I replaced the call that opens the file in com.omt.epubreader.domain.epub.java, so it became like this:
public Book getBook(String url)
{
InputStream in = ConnectionController.GetFileAsStream(url);
...
return book;
}
after that, I could read the file successfully, but a problem appeared, it wasn't able to read the sections, i.e. the .html files, so I went into a short debug session before I found the problem, whoever wrote that library, left the code that read the .html file names empty, in com.omt.epubreader.parser.NcxParser it was like this:
private void getBookNcxInfo()
{
...
if(pars.getEventType() == XmlPullParser.START_TAG &&
pars.getName().toLowerCase().equals(TAG_CONTENT))
{
if(pars.getAttributeCount()>0)
{
}
}
...
}
I just added this line to the if clause:
contentDataFileName.addElement(pars.getAttributeValue("", "src"));
and after that, it worked just perfectly.
Can any one please help me how to get the real file name from Struts2 MultiPartRequestWrapper.
MultiPartRequestWrapper multiWrapper =
(MultiPartRequestWrapper) ServletActionContext.getRequest();
Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
if(fileParameterNames.hasMoreElements()){
String inputValue = (String) fileParameterNames.nextElement();
File[] files = multiWrapper.getFiles(inputValue);
for (File cf : files) {
System.out.println(cf.getParentFile().getName());
System.out.println("cf is : " + cf.getName());
System.out.println("cf is : " + cf.toURI().getPath());
File.createTempFile(cf.getName(),"");
}
}
I can see original file name, type, size from "fileParameterNames" but when get file I can only see tempfile with upload_xxxxxxxxx.tmp.
How can I get original file name from the File.
Advance thanks for your help.
Why are you doing all that?
See the file upload FAQ and details pages. All you need to do is provide the appropriate action properties:
public void setUploaded(File myDoc);
public void setUploadedContentType(String contentType);
public void setUploadedFileName(String filename);
and use the file upload interceptor, which is included in the default stack.
Note that different browsers send different information; some only send the original filename, while some send the complete path.
You have to use : multiWrapper.getFileNames("file")[0]
Where "file" is the name of the file control.
var fd = new FormData();
fd.append('file', files[i]);
I have the following issue:
I have a MVC application, in some action of some controller i'm generating a PDF file, the file is being generated on a specific path on the server. That action is being called on an action link of the view, when the user clicks that link, the action generated that PDF, everything fine until here.
I want the page to show the dialog with my generated PDF file that says:
Open - Save - Cancel (the tipical file dialog when you click a file)
But without refreshing the page, only show the dialog when the user clicked the link.
How could i do that? what should the action return to the view?
Thanks.
Have a look at FilePathResult and FileStreamResult.. An example is here.
To provide the Open - Save - Cancel dialog you will need to set the appropriate Response headers, and as #RichardOD says, return a FilePathResult or FileStreamResult.
HttpContext.Response.AddHeader("content-disposition", "attachment;
filename=form.pdf");
return new FileStreamResult(fileStream, "application/pdf");
Try something like this
public class PdfResult : ActionResult
{
//private members
public PdfResult(/*prams you need to generate that pdf*/)
public override void ExecuteResult(ControllerContext context)
{
//create the pdf in a byte array then drop it into the response
context.HttpContext.Response.Clear();
context.HttpContext.Response.ContentType = "application/pdf";
context.HttpContext.Response.AddHeader("content-disposition", "attachment;filename=xxx.pdf");
context.HttpContext.Response.OutputStream.Write(pdfBytes.ToArray(), 0, pdfBytes.ToArray().Length);
context.HttpContext.Response.End();
}
}
Then u just return a PdfResult
Tip: I got a generic class for doing this and it's something like this and i am using NFop
public PdfResult(IQueryable source, Dictionary<string,int> columns, Type type)
{
Source = source;
Columns = columns;
SourceType = type;
}