I want to save the file which is uploaded using struts 2 with different filename
orginal filename is like xyz.xls to xyz-jan-01.xls
Uploaded files are available as Files in the action. Move it using Commons IO's moveFile method.
See the file upload FAQ entry and file upload interceptor docs for details.
The code shall look something like this
public String execute() {
try {
String filePath = ServletActionContext.getServletContext().getRealPath("/uploads");
System.out.println("Server path:" + filePath);
File fileToCreate = new File(filePath, "NewFileName");
FileUtils.copyFile(this.userImage, fileToCreate); //userImage is a File
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
You can find the complete example here.
Related
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);
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
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've got a pop-up textarea, where the user writes some lengthy comments. I would like to store the content of the textarea to a file on the server on "submit". What is the best way to do it and how?
THanks,
This would be very easy to do. The text could be just a string or stringBuffer for size and formatting, then just pass that to your java code and use file operations to write to a file.
This is some GWT code, but it's still Ajax, so it will be similar. Get a handler for an event to capture the button submittal, then get the text in the text area.
textArea.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent changeEvent) {
String text = textArea.getText();
}
});
The passing off mechanism I don't know because you don't show any code, but I just created a file of filenames, line by line by reading filenamesout of a list of files with this:
private void writeFilesListToFile(List<File> filesList) {
for(File file : filesList){
String fileName = file.getName();
appendToFile(fileName);
}
}
private void appendToFile(String text){
try {
BufferedWriter out = new BufferedWriter(new FileWriter<file path andfile name>));
out.write(text);
out.newLine();
out.close();
} catch (IOException e) {
System.out.println("Error appending file with filename: " + text);
}
}
You could do something similar, only write out the few lines you got from the textarea. Without more to go on I can't really get more specific.
HTH,
James