How can I read the content of an uploaded file in the execute() method of the Action class? I am able to upload the file on the server but do not know how to read the content of that file.
Do we have to first save it on the server? Or can we read it directly?
Option 1: Create a servlet
I recommend you utilize apache commons file upload. This link has examples on how to process the uploaded file (writing it to a disk or reading it in memory if the file size is small enough) using FileItem. Another relevant example can be found here.
Option 2: using the struts s:file tag
As #BalusC mentioned in the comments below struts has a built in file upload process using s:file tag library and a tutorial of using it is provided here. Essentially the file gets uploaded to a temporary directory. However, you can override that by setting a value for the struts.multipart.saveDir property in the default.properties file. This link also mentions using Apache FileUtils to process the uploaded file afterwards which by the way is a very handy library for any File I/O work.
http://java.dzone.com/articles/struts2-tutorial-part-67 Here he explains how to make a very clear and detailed upload
Here's the standard way that provides Struts2, with an example:
http://struts.apache.org/2.0.14/docs/file-upload.html
It's quite simple and elegant (no need to mess with servletRequest.getRealPath("/") as ther other example linked by hoss).
By using the <s:file> tag (and the appropiate interceptor), Struts2 makes all the dirty work and gives you the (temporary) uploaded file as a File field in the action; you can open it or move, or whatever, as you do with any file.
Related
I need to write a little Grails (or Java) app that will handle authentication (from our proprietary Single Sign On system) and then once authenticated allow a user to download files. This is very straight forward if I simply include the files in the WAR file of the application, however, I'd like to avoid that since there will be multiple files and I'd rather not have to upload a new WAR file every time we add a new file. Is it possible to accomplish this by having the application be in a WAR file but the files outside the WAR file, if so, how do I configure this kind of setup? We'll be running this on Tomcat.
Yes this is possible. Without knowing all your requirements or what you have tried and why it didn't work work for you the best I can do is give you a general idea of how to accomplish this.
Have a controller that takes an ID of the file that you want the user to download. Based on this key find the associated Domain instance. The domain should store the file name of the file. Then use this file name to resolve the file from the local file system (path configured in your application configuration). Open the file and stream the contents to the browser. Be sure to set he headers correctly to indicate the file name and size.
There are a lot of moving parts involved here but it can be done. Now, if you get stuck on something I suggest you post what you have tried and what's not working about it. Otherwise, the best we/I can do is give you general guidance/advice.
Hope this helps!
Edit
The real key is going to be in the controller for downloading the files. Here is a quick snippet of what that may look like:
String fileName = "something.zip" // should come from your domain instance
String filePathAndName = "/downloads/${fileName}" // should come from your configuration
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "attachment;filename=${fileName")
// this will actually buffer/stream the file in 8k chunks instead of reading the entire file into memory.
org.apache.commons.io.IOUtils.copy((new File(filePathAndName)).openStream(), response.outputStream)
response.outputStream.flush()
response.outputStream.close()
Right now I'm working on an archive browsing application that lets users navigate through archive contents, extract the archives and preview the files inside the archive. I'm using java.util.zip API. To preview a file I'm extracting it temporarily and opening it as a usual existing file. As you may understand, that's not a good approach since it won't preview files if there's not enough space to make a temporary extraction. Is there a working solution for passing ZipInputStream to an Activity to open it as a file? Is there another workaround for this problem? Thanks in advance.
In principle, you could create a ContentProvider that serves up the ZipInputStream.
In this sample project I demonstrate how to create a ContentProvider supporting openFile() that uses a pipe created by ParcelFileDescriptor.createPipe() to serve up a file. createPipe() returns a pair (two-element array) of ParcelFileDescriptors representing the ends of the pipe. You use the second element out of the array to write to via an OutputStream; openFile() returns the first element out of the array to be passed by Android to the calling process. The caller would use openInputStream() to read in what you transfer via the pipe.
In my case, I am sending an asset on which I get an InputStream via AssetManager. In your case, you would use your ZipInputStream.
Note that my sample project assumes it is being run on a device that has a PDF viewer, since it is serving a PDF out of assets and trying to open it via startActivity().
So I'm writing a Spring web application that runs some scripts on the local server using ProcessBuilder. That part seems to be running fine. The scripts generate output files and then zip them up into a single .zip file. I'd like to provide the user with a way to download these files but I'm not sure of the best way to do this, or even how to implement any way to do it.
I tried putting the path to the directory into the URL, but I believe since Spring intercepts all URLs and it doesn't know how to process the one pointing at either the directory the Zip is in or the Zip itself, I just get an error. What would the proper way to do this be? Either to display a list of files or just link to the files themselves? Any help would be really appreciated, thank you.
The way you do any file download from a web-app is to write a servlet that writes the content of the file to the http response's output stream. There's an example of this here that's downloading an Excel file.
The directory listings that you get in a web-page don't just happen automatically, you'll have to write a JSP that displays the directory listing with hyperlinks on each file that link to file download servlet.
I looked around and could not find a complete directory listing example for spring. Though it is relatively simple to implement I put together a blog post to explain this, so that it could be quickly reused when needed http://krishna-passionatelycurious.blogspot.com/2013/04/file-download-page-using-spring.html.
But, the overall approach is to loop through the contents of a directory and generate appropriate links, such that the links point back to the same spring handler, where we could make a decision based on whether the accessed link actually points to a directory or a file and generate directory listing again or stream the content for download.
The blog has a sample implementation of this.
I would like to transfer a file from the Flex front end to a back end Java web service, how can I achieve this ?
Will byte array be a good option for the transfer ?
It would be appreciated if you can give a hint as to how to achieve the solution or point me in the right direction.
Note: the file is a small .jpg file, and I am new to Java
Have a look on http://www.adobe.com/devnet/flex/articles/file_upload.html
You can use Flex "FileReference class" to Upload a file on Server
Flex Working with file upload and download
and commonly on server there should be a servlet to accept multipart request
using
Apache Commons FileUpload
this is useful example of servlet
Servlet File Upload Example
Hopes that helps
I have used a byte array to transfer files when I know they will be small. It can be a lot simpler to post them when dealing with https/cert issues, etc. that FileReference does not work well with. A FileReference upload is your other option (typical solution). Either way you'll use FileReference to select the file and then either use .upload to upload it or .load to load bytes in. Then you'll use .data to get the byte array. If your Jpg is coming from a snapshot taken from a flex component in memory, you'll need to work with a special Jpeg image encoder. I can tell you how to do that if that is what you are doing. Really beyond the scope of your original question, though.
I need some ideas on how I can best solve this problem.
I have a JBoss Seam application running on JBoss 4.3.3
What a small portion of this application does is generate an html and a pdf document based on an Open Office template.
The files that are generated I put inside /tmp/ on the filesystem.
I have tried with System.getProperties("tmp.dir") and some other options, and they always return $JBOSS_HOME/bin
I would like to choose the path $JBOSS_HOME/$DEPLOY/myEAR.ear/myWAR.war/WhateverLocationHere/
However, I don't know how I can programatically choose path without giving an absolute path, or setting $JBOSS_HOME and $DEPLOY.
Anybody know how I can do this?
The second question;
I want to easily preview these generated files. Either through JavaScript, or whatever is the easiest way. However, JavaScript cannot access the filesystem on the server, so I cannot open the file through JavaScript.
Any easy solutions out there?
Not sure how you are generating your PDFs, but if possible, skip the disk IO all together, stash the PDF content in a byte[] and flush it out to the user in a servlet setting the mime type to application/pdf* that responds to a URL which is specified by a link in your client or dynamically set in a <div> by javascript. You're probably taking the memory hit anyways, and in addition to skipping the IO, you don't have to worry about deleting the tmp files when you're done with the preview.
*****I think this is right. Need to look it up.
Not sure I have a complete grasp of what you are trying to achieve, but I'll give it a try anyway:
My assumption is that your final goal is to make some files (PDF, HTML) available to end users via a web application.
In that case, why not have Apache serve those file to the end users, so you only need your JBOSS application to know the path of a directory that is mapped to an Apache virtual host.
So basically, create a file and save it as /var/www/html/myappfiles/tempfile.pdf (the folder your application knows), and then provide http://mydomain.com/myappfiles (an Apache virtual host) to your users. The rest will be done by the web server.
You will have to set an environment variable or system property to let your application know where your folder resides (/var/www/html/myappfiles/ in this example).
Hopefully I was not way off :)
I agree with Peter (yo Pete!). Put the directory outside of your WAR and setup an environment variable pointing to this. Have a read of this post by Jacob Orshalick about how to configure environment variables in Seam :
As for previewing PDFs, have a look at how Google Docs handles previewing PDFs - it displays them as an image. To do this with Java check out the Sun PDF Renderer.
I'm not sure if this works in JBoss, given that you want a path inside a WAR archive, but you could try using ServletContext.getRealPath(String).
However, I personally would not want generated files to be inside my deployed application; instead I would configure an external data directory somewhere like $JBOSS_HOME/server/default/data/myapp
First, most platforms use java.io.tmpdir to set a temporary directory. Some servlet containers redefine this property to be something underneath their tree. Why do you care where the file gets written?
Second, I agree with Nicholas: After generating the PDF on the server side, you can generate a URL that, when clicked, sends the file to the browser. If you use MIME type application/pdf, the browser should do the right thing with it.