I am uploading a file with the PF 3.5 File Uploader
My Upload Method looks like that:
public void handleFileUpload(FileUploadEvent event) {
log.info("Method handleFileUpload invoked");
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
InputStream inputStream = null;
OutputStream out = null;
try {
File targetFolder = new File("\\resources\\uploads");
if(!targetFolder.exists()) {
targetFolder.mkdirs();
}
inputStream = event.getFile().getInputstream();
File outFile = new File(targetFolder, event.getFile().getFileName());
log.info("copy file stream to " + outFile.getAbsolutePath());
out = new FileOutputStream(outFile);
int read = 0;
byte[] bytes = new byte[size];
log.info("read file stream");
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
} catch (IOException e) {
log.error(e);
} finally {
...
}
at the moment my files get uploaded to \\resources\\uploads". Thats the path to a folder on theC:`.
However, I want to upload my uploads to a path in my eclipse project. How to change the path? I really appreciate your answer!!!
However, I want to upload my uploads to a path in my eclipse project.
That's absolutely not recommended for the reasons mentioned in this answer: Uploaded image only available after refreshing the page. The point is: the IDE's workspace and server's deploy folder is absolutely not intented as a permanent file storage. The uploaded files would be unreachable and/or disappear like by magic.
Just keep them in a path external to the IDE's workspace and server's deploy folder. You're doing it fine. I'd only make the path configurable by a system property, environment variable or properties file setting so that you don't need to edit, recompile, rebuild, etc the code everytime when you change the upload location.
If your concrete problem is more the serving of the uploaded file, then just add the upload folder as another context in server's configuration, or create a simple servlet for the serving job, or as you're using PrimeFaces, just use <p:fileDownload> or <p:graphicImage> with StreamedContent pointing to the desired FileInputStream.
See also:
How to save uploaded file in JSF
Related
I am using:
Eclipse Java EE IDE for Web Developers version: Mars.2 Release (4.5.2);
Apache Tomcat v8.0;
a Web Dynamic project;
a Java Servlet.
I have a JSON file stored in the ./WebContent folder. I am trying to get the absolute path of the JSON file in this way:
ServletContext sc = request.getSession().getServletContext();
//String absolutePath = "/Users/kazuhira/Documents/MAC_workspace/lab2_calendario/WebContent/Database/Events.json";
String relativePath = "eventsBackup.json";
String filePath = sc.getRealPath(relativePath);
System.out.println("(saverServlet): the path of the file is "+filePath);
//System.out.println("(saverServlet): the path of the file is "+absolutePath);
//File file = new File(absolutePath);
String content = request.getParameter("jsonEventsArray");
try (FileOutputStream fop = new FileOutputStream(file)) {
System.out.println("(saverServlet): trying to access to the file"+filePath);
// if file doesn't exists, then create it
if (!file.exists()) {
System.out.println("(saverServlet): the file doesn't exists");
file.createNewFile();
System.out.println("(saverServlet): file "+filePath+" created");
}
System.out.println("(saverServlet): writing on the file "+filePath);
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("(saverServlet): events backup done");
} catch (IOException e) {
e.printStackTrace();
}
and the file path reconstructed from the relativePath is:
/Users/kazuhira/Documents/MAC_workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/lab2_calendario/testJson.txt
Why String filePath = sc.getRealPath(relativePath); generates a path on a temporary folder? In which way I can configure the context on the "real" json file (the same I create in the project)?
I suppose Tomcat is working in a temporary context, why? There's a way to tell him to use the same folder of the project?
Yes, you can by changing an option in your Server configuration in Eclipse
Select the second option in the radio button list :)
I'm developing a java based application using NetBeans.
What i want to do:
My project folder includes a resources folder which contains all the Images that are needed by the project for basic stuff (setting background,icons etc).
Now suppose end user wants to save an new Image on the run time. File Chooser opens up. User selects a source(.jpg) file and the image gets copied. What i want is, to save this image to my resources folder rather than on LocalDisk path. I'm having no trouble copying this image to a LocalDisk path.
Is there any way through which i can do this?
My resource folder path is:
(ProjectName)\src\resources
Code I'm using to save image to Local Address:
InputStream input = null;
OutputStream output = null;
String fileName = itemId.getText();
try
{
input = new FileInputStream(srcPath.getText()); //Getting Source File Absolute Path Through FileChooser
output = new FileOutputStream("C:\\Users\\BUN\\Documents\\Folder\\"+fileName+".jpg");
byte[] buf = new byte[1024];
int bytesRead;
while((bytesRead = input.read(buf))>0)
{
output.write(buf,0,bytesRead);
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
Thank's in advance!
I need to save a directory of resource files from the currently running JAR file to a temporary directory on the user's disk.
Currently, I'm saving files one by one. But now I have a large folder of native libraries to save that I would rather not save this way.
I tried my current code, just in case it treated the directory as a file and saved it anyway.
public void saveResource(String name, File outFile) {
try (InputStream in = this.getClass().getResourceAsStream(
name);
OutputStream out = new FileOutputStream(outFile);) {
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
But sadly, it didn't work. So what's the best way to save a directory of resources to disk?
You need to loop through all the files in that folder and save the files one by one. I guess this is what you are doing now. You can't copy the folder entirely.
or you can use commons-io FileUtils
Im trying to access the example/web folder (see below in the image) in a jsf managed bean but cant seem to find a way to do it
thx
Try
FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath()
for build relative url's to resources in your app.
If you want the real path...
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
.getExternalContext().getContext();
String realPath = ctx.getRealPath("/");
If you want to get it as a File for some reason, then you need ExternalContext#getRealPath(). This converts a relative web path to an absolute disk file system. Since you need the web's root folder, just pass in /:
String absoluteWebPath = externalContext.getRealPath("/");
File webRoot = new File(absoluteWebPath);
// ...
Unrelated to the concrete problem, whatever functional requirement you've had in mind for which you thought that having an absolute local disk file system path to the web folder is the right solution, it has most definitely to be solved differently. And indeed, as per your comment on the other answer,
because Im trying to upload some file inside the folder and using the relative path
you're going the wrong path. You should not store uploaded files in there if you intend to keep them longer than the webapp's deployment lifetime. Whenever you redeploy the webapp (and on some server configs even when you restart the server), the uploaded files would get completely lost, simply because they are not contained as part of the original WAR file. Even more, some heavy server configs don't expand the WAR on disk at all, but in memory instead, the getRealPath() would then always return null.
Rather store it in a fixed disk file system path outside the server's deploy folder. Add that path in turn as a new server context or docroot, so that it's accessible on a different (virtual) context path. Or homegrow a servlet which gets an InputStream of it from disk and writes it to OutputStream of the response. See also this related answer: Uploaded image only available after refreshing the page
Try:
String relativePath="/resources/temp/";
String absolutePath= FacesContext.getCurrentInstance.getExternalContext().getRealPath(relativePath);
File file = new File(absolutePath);
to get real path.
Create a tmp file in resources/temp/ to avoid any exception.
Just wanted to thank Balus C. Code Java with JSP, in Tomcat/Tomee server I the following code that works:
private Boolean SaveUserItemImage(Part ui, String bid) throws IOException {
Boolean fileCreate = false;
OutputStream out = null;
InputStream filecontent = null;
ExternalContext ctx = context().getExternalContext();
String absoluteWebPath = ctx.getRealPath("/");
String resource_path = absoluteWebPath + "\\resources\\";
String image_path = resource_path + "\\" + this.itemType + "_images\\";
String buildFileName = image_path + bid + "_" + getFileName(ui);
File files = null;
try {
files = new File(buildFileName);
fileCreate = true;
} catch (Exception ex) {
System.out.println("Error in Creating New File");
Logger.getLogger(ItemBean.class.getName()).log(Level.SEVERE, null, ex);
}
if (fileCreate == true) {
if (files.exists()) {
/// User may be using same image file name but has been editted
files.delete();
}
try {
out = new FileOutputStream(files);
filecontent = ui.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
fileCreate = true;
} catch (FileNotFoundException fne) {
fileCreate = false;
Logger.getLogger(ItemBean.class.getName()).log(Level.SEVERE, "SaveUserItemImage", fne);
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
files = null;
}
}
return fileCreate;
}
I am developing and application using eclipse IDE. My application has a file upload functionality.
I am able to achieve how to upload the file and also to save it. But the problem is that the file uploaded didn't get store to my dynamic web project directory.
The file uploaded get store to my server directory with .metadata folder having path
file:///E:/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/
I want to store my uploaded folder to my Webcontent folder having upload folder having images folder like WebContent/upload/images.
No doubt I am able to view the image file but, the path i want is like above only.
below code I am using to store the uploaded file
#RequestMapping(value = "/company/UploadFile.action", method = RequestMethod.POST)
public #ResponseBody String uploadFile(FileUploadBean uploadItem, BindingResult result,HttpServletRequest request, HttpServletResponse response) {
System.out.println("FILE UPLOAD ITEM SI SSLSL ::"+uploadItem);
ExtJSFormResult extjsFormResult = new ExtJSFormResult();
if (result.hasErrors()){
for(ObjectError error : result.getAllErrors()){
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}
//set extjs return - error
extjsFormResult.setSuccess(false);
return extjsFormResult.toString();
}
// Some type of file processing...
System.err.println("-------------------------------------------");
System.err.println("Test upload: " + uploadItem.getFile().getOriginalFilename());
System.err.println("-------------------------------------------");
try{
MultipartFile file = uploadItem.getFile();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (file.getSize() > 0) {
inputStream = file.getInputStream();
/*if (file.getSize() > 10000) {
System.out.println("File Size:::" + file.getSize());
extjsFormResult.setSuccess(false);
return extjsFormResult.toString();
}*/
System.out.println("also path ::"+request.getRealPath("") + "/upload/images/");
System.out.println("PATHI SIS SIS"+this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
System.out.println("size::" + file.getSize());
InetAddress addr = InetAddress.getLocalHost();
byte[] ipAddr = addr.getAddress();
System.out.println("HOST NAME"+request.getRealPath("ResourceMgt"));
System.out.println("HOST ADDR"+addr.getHostAddress());
System.out.println("HOST "+request.getRequestURI());
System.out.println("HOST "+request.getRequestURL());
fileName = request.getRealPath("") + "/upload/images/"
+ file.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("FILEN ANEM AND PATH IS ::"+fileName);
System.out.println("fileName:" + file.getOriginalFilename());
int readBytes = 0;
byte[] buffer = new byte[40000];
while ((readBytes = inputStream.read(buffer, 0, 40000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
companyservice.saveImages(file.getOriginalFilename(),fileName);
outputStream.close();
inputStream.close();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//set extjs return - sucsess
extjsFormResult.setSuccess(true);
return extjsFormResult.toString();
}
please suggest me how can I store the file uploaded to my WebContent having upload folder with images folder. My above code is working perfectly Just there is some issue with specifying the path.
Have you tried to change the destination of the outputStream?
fileName = request.getRealPath("") + "/upload/images/"
+ file.getOriginalFilename();
Instead of request.getRealPath("") put an absolute destination or play with ClassPath. For example:
fileName = "/opt/tomcat/webapps/upload/images/"
+ file.getOriginalFilename();
forum member
now I am able to upload the file successfully, but the file get stored to the deployed directory on the server.
As soon as I remove the project and redeployed the project to my Tomcat server 6.0 all the files I had uploaded gets deleted from that.
I am using JAVA as my server side technology with Tomcat server 6.0.
I am able to upload the file successfully, but the file get stored to the deployed directory on the server.
As soon as I remove the project and redeployed the project to my Tomcat server 7.0 all the files I had uploaded gets deleted from that.
I am using JAVA and JSF as my server side technology with Tomcat server 7.0 in Eclipse IDE