Glassfish - uploading images - doing it right

大城市里の小女人 提交于 2019-12-04 10:10:24

Good practice is to pick a path on the filesystem where photos will be uploaded. Often this path is programmed to be configurable via java system property (eg: by passing -Dcom.mycompany.uploadPath=/path/to/photos/dir system property on JVM arguments).

You can also use java system propeties to find environment specific path: user.dir, user.home etc. See System Properties on Java SE Tutorial. Or to use glassfish-relative path, see glassfish system properties.

Once you have reference to Part, it's just about doing file IO to copy the uploaded file into this upload path, eg:

Part part = // obtain part somehow..
String photoFileName = // build a file name somehow..
InputStream photoInputStream = part.getInputStream();
FileOutputStream photoOutputStream = new FileOutputStream(System.getProperty("com.mycompany.uploadPath") + File.separator + photoFileName);
IOUtils.copy(photoInputStream, photoOutputStream);
// close streams here...

Code above uses apache IOUtils for convenience but feel free to write your own copy method. You should also add exception handling method

Mr_and_Mrs_D

What is StoreLocation ? How tmp are those glassfish uploads ? Where are all those parameters set ?

StoreLocation is just the the java.io.File object for the FileItem's data's temporary location on the disk. Resides in javax.servlet.context.tempdir which defaults to %GLASSFISH_HOME%\domains\domain1\generated\jsp\webApp. Those uploads are as tmp as anything (The lifetime of the file is tied to the lifetime of the FileItem instance; the file will be deleted when the instance is garbage collected - from here). Haven't yet managed to change the value of javax.servlet.context.tempdir programmatically (comment please) - it is the tempdir property of the sun-web-app element of the sun-web.xml.

What would be a more professional way of handling the situation - including keeping the photos outside the webroot - but using facilities glassfish provides (if it does provide) ?

Well a more professional way is to Use Part.write() to move the file to the desired location. Due to glassfish implementation though you can't supply an absolute path to write - a chore. I asked here.

As to where to save the file : https://stackoverflow.com/a/18664715/281545

That is for saving the file - to serve it from a location outside the app you need to define "alternatedocroot" properties in the sun-web.xml (or glassfish-web.xml).

Even p1 printing so nice escapes me (it does not seem to Override toString())

Oh yes it does

Interested in tips even in how should one rename the photos etc (is this sessionID thing Right ? - check also the time trick)

No it is not - I tend towards File#createTempFile() - anyway this is a different question asked here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!