I would like to upload an image and store it on the server, and later to show it with h:graphicImage? I would like to store it in "resources/images" of the app. I am using glassfish 4. Right now, the file goes to "domain1\generated\jsp\FileUpload". Thank you
My form
<h:form id="form" enctype="multipart/form-data">
<h:messages/>
<h:panelGrid columns="2">
<h:outputText value="File:"/>
<h:inputFile id="file" value="#{uploadPage.uploadedFile}"/>
</h:panelGrid>
<br/><br/>
<h:commandButton value="Upload File" action="#{uploadPage.uploadFile}"/>
</h:form>
My bean
@Named
@ViewScoped
public class UploadPage {
private Part uploadedFile;
public void uploadFile(){
File file = File.createTempFile("somefilename-", ".jpg", new File("C:\\var\\webapp\\images"));
uploadedFile.write(file.getAbsolutePath());
}
}
I would like to store it in "resources/images" of the app
No, please don't. The WAR deploy space isn't intented as permanent file storage location. All of those uploaded files would get lost whenever you redeploy the webapp for the very simple reason that they are not contained in the original WAR. See for an elaborate explanation also this answer on a very closely related question: Uploaded image only available after refreshing the page.
Right now, the file goes to "domain1\generated\jsp\FileUpload".
Because you specified a relative path in Part#write()
. It becomes relative to the current working directory which you have no control over. See for an elaborate explanation also this related answer: getResourceAsStream() vs FileInputStream. You need to specify an absolute path, in other words, start the path with /
.
Given that you're using Glassfish, the answer in Uploaded image only available after refreshing the page should also do it for you. In a nutshell:
Create a
/var/webapp/images
folder. Note that this path is just examplary and fully free to your choice. Also note that when you're using Windows with aC:\
disk, then this path is equivalent toC:\var\webapp\images
.Save the uploaded file in there.
Path file = Files.createTempFile(Paths.get("/var/webapp/images"), "somefilename-", ".jpg", ); try (InputStream input = uploadedFile.getInputStream()) { Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING); } imageFileName = file.getFileName().toString(); // ...
(note:
Files#createTempFile()
is being used to autogenerate an unique filename, otherwise a previously uploaded file would get overwritten when the new uploaded file (by coincidence) has exactly the same filename)Tell GlassFish to register a virtual host on
/var/webapp/images
so that all files are available onhttp://example.com/images
by adding the following entry to/WEB-INF/glassfish-web.xml
of the webapp:<property name="alternatedocroot_1" value="from=/images/* dir=/var/webapp" />
(note:
alternatedocroot_1
must be exactly like that, keep it unmodified, if you have multiple, name italternatedocroot_2
, etc; also note that the/images
part should indeed not be included indir
attribute, this is not a typo)Now you can display it as follows:
<h:graphicImage value="/images/#{bean.imageFileName}" />
(note: use
value
attribute, notname
attribute)
Wasn't able to get it working with Path#write
in glassfish, so I used Path#getInputStream
as follows:
public void upload(){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
String filename = getFilename(uploadedFile);
File file = new File("/var/webapp/images/"+filename);
bis = new BufferedInputStream(uploadedFile.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
int x;
while((x = bis.read())!= -1){
bos.write(x);
}
} catch (IOException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
bos.flush();
bos.close();
bis.close();
} catch (IOException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private static String getFilename(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
来源:https://stackoverflow.com/questions/19139426/how-to-write-a-file-to-resource-images-folder-of-the-app