Almost all java examples showing how to send an email set dummy file path. But actually we don't know the path before file selection. I have already known input=file can't get the full path of the file due to security problems. Then how can I get the path as email function must use path?
Here is the part in most examples that would use file path
String path = "D:\\jar\\java-json.jar";
String fileName = "java-json.jar";
DataSource source = new FileDataSource(path);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
Have you tried Apache Commons Email library?
It has features for email attachments, and it has built-in support for java servlet integration.
OK, at last it shows most java email examples on Internet are not useful for web browsers as web browser can't get full path of a file. At last I use the InputStream to get the file and put it into the DataSource. These two lines are the keys:
InputStream filecontent = filePart.getInputStream();
DataSource source = new ByteArrayDataSource(filecontent, "Text/txt");
If you are using 'java-mail-1.4.*.jar' then simply do this...
you use 'JFileChooser' to create file chooser popups, then may be (say) in your actionListner method for a button do the following -
filepath = fc.getSelectedFile().getAbsolutePath();
where 'filepath' is a String, and 'fc' is a object to 'JFileChooser' class
Related
i'm using OutputStream to create a pdf file for download as follow:
byte[] infoFile = info.getBytes();
String infoName = info.getFileName();
String contentType = info.getContentType();
response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment;filename=\"" + infoName + "\"");
response.setContentLength(infoFile.length);
// till now no problem, the file name is ok
OutputStream out = response.getOutputStream();
out.write(infoFile);
//here, as soon as the previous line is executed a file is generated with wrong characters
// ex. D:__Profiles__User__Downloads__infoFile.pdf
Here the file produced is something like "D:__Profiles__User__Downloads__infoFile.pdf"
while i expect the file "D:\Profiles\User\Downloads\infoFile.pdf"
What's wrong?
What's wrong?
Your expectation that the filename in a Content-disposition header should have path information.
From RFC 6266 section 4.3
Recipients MUST NOT be able to write into any location other than
one to which they are specifically entitled. To illustrate the
problem, consider the consequences of being able to overwrite
well-known system locations (such as "/etc/passwd"). One strategy
to achieve this is to never trust folder name information in the
filename parameter, for instance by stripping all but the last
path segment and only considering the actual filename (where 'path
segments' are the components of the field value delimited by the
path separator characters "" and "/").
And similarly in the Mozilla docs
The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done.
Basically you should only be specifying infoFile.pdf. It's up to the user which directory that file is saved in.
I have a little problem with Struts 2 when I try to get the context path :
ServletActionContext.getServletContext().getRealPath("\\WebContent\\resources\\img\\");
I got this path:
C:\Users\killian\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SiteWebAdministrable\WebContent\resources\imgicone.jpg
Why the exact source path ?
Because i need to upload and save images for an admin website to control background and without the actual path i cannot save images in the resources path...
So i save the path with the name and extension in the database (no problem), and i need to save the image in the resource directory (image problem...)
Can someone help me please ? Did i forgot something ?
This question is the answer ?
How do you get the project path in Struts 2?
servletContext.getServletContext().getRealPath("/resources/img/name_of_image.png")
So, passing the "/" to getRealPath() would return you the absolute disk file system path of the /web folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/demo.war/ which you should be able to further use in File or FileInputStream.
Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use
String absolutePathToIndexJSP = servletContext.getRealPath("/") + "demo.png";
instead of
String absolutePathToIndexJSP = servletContext.getRealPath("/demo.png");
getRealPath() is unportable; you'd better never use it
Use getRealPath() carefully.
If all you actually need is to get an InputStream of the web resource, better use ServletContext#getResourceAsStream() instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream of index.jsp, then do not do:
InputStream input = new FileInputStream(servletContext.getRealPath("/demo.png")); // Wrong!
But instead do:
InputStream input = servletContext.getResourceAsStream("/demo.png"); // Right!
Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths() instead.
Set<String> resourcePaths = servletContext.getResourcePaths("/");
I want to get the URIs to the entries of a zip file in order to keep references to it's contents without having to keep the zip file open.
Therefore I open the zip file using the zip filesystem and export the Path of the entries as URI.
Path zipfile = ...
URI uriOfFileInZip;
try(FileSystem fs = FileSystems.newFileSystem(zipfile, null)){
Path fileInZip = fs.getPath("fileInZip.txt");
uriOfFileInZip = fileInZip.toUri();
}
Now I want to read the file again, so I try to open a stream to the file.
InputStream is = uriOfFileInZip.toURL().openStream();
This works as long as the path of the zip file does not contain any spaces. As soon as it contains spaces, I get an error like this
java.io.FileNotFoundException: D:\example\name%20of%20zipfile.zip (The system cannot find the file specified)
the URI to the file in the zip is
jar:file:///D:/example/name%2520of%2520zipfile.zip!/fileInZip.txt
the name of the zip is
D:\example\name of zipfile.zip
I wonder about the %2520 this seems like an issue with the URL encoding, but shouldn't this be handled transparently? Or is it a bug?
Any ideas to solve this problem?
Looks like a bug.
Seems as if com.sun.nio.zipfs.ZipPath.toUri() is either messed up, or I didn't read the corresponding RFC yet ;-). Played around with some other file names. There seems to be a double encoding going on for the zip file path, but not for the file entry in the zip.
Besides not using the URI-approach you could also build the URI yourself from scratch, but then you are not that flexible anymore. Or you just undo the unnecessary encoding:
String uriParts[] = uriOfFileInZip.toString().split("!");
uriParts[0] = URLDecoder.decode(uriParts[0], "UTF-8");
uriOfFileInZip = URI.create(String.join("!", uriParts));
But to be honest, I would rather try to omit the URI for zip files or if you really have to, rename the files beforehand ;-) Better yet: open a bug if it does not behave as stated in the corresponding RFCs.
You may also want to get some additional information from the following question regarding bug, etc.:
Java 7 zip file system provider doesn't seem to accept spaces in URI
EDIT (added proposal without URI):
You can also try to completely work with your Path instance (fileInZip) instead of the URI, as the path instance "knows" its filesystem.
As soon as you need access to the file inside the zip, you create a new FileSystem based on the information of the Path instance (fileInZip.getFileSystem()). I did not elaborate that completely, but at least the file store should contain all the necessary information to access the zip file again. With that information you could call something like FileSystems.newFileSystem(Paths.get(fileStoreName), null).
Then you can also use Files.newInputStream(fileInZip) to create your InputStream. No need to use URI here.
This is only reproducible with JDK 8. The later versions do not have this issue.
For the following code:
Map<String, String> env = new HashMap<>();
env.put("create", "true");
final FileSystem fs = FileSystems.newFileSystem(new URI("jar:file:/D:/path%20with%20spaces/junit-4.5.jar"), env);
System.out.println(fs.getPath("LICENSE.TXT").toUri()); `
I got the following output with JDK 1.8.0_212 :
jar:file:///D:/path%2520with%2520spaces/junit-4.5.jar!/LICENSE.TXT
whereas with JDK 11.0.3:
jar:file:///D:/path%20with%20spaces/junit-4.5.jar!/LICENSE.TXT
A search through the Java bug system shows that it had been fixed in JDK 9 with JDK-8131067 .
I have a homepage, which has a directory for downloads.
I want to read all files of this homepage automatically, from its directory.
For example I have the homepage: www.homepage.org and the subdirectory resources/downloads with the download files I want to show.
I have a Java Server with Spring and JSPs running and tried the following, which didn't work at all:
String path = request.getContextPath();
path += DOWNLOADS;
URL url = null;
String server = request.getServerName();
try {
url = new URL("https", server, request.getLocalPort(), path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url != null) {
String externalForm = url.toExternalForm();
File directory = new File(externalForm);
String[] files = directory.list();
for (String file : files) {
;
}
}
You can use a Servlet. If your resources directory is in your web app's root directory, then use
PrintWriter writer = response.getWriter();
String path = getServletContext().getRealPath("/resources/downloads");
File directory = new File(path);
if(directory.isDirectory()){
String[] files = directory.list();
for (String file : files) {
writer.write(file + "<br/>");
}
} else writer.write(directory.getAbsolutePath() + "could not be found");
I found a solution with using a FTP manager...
You can view the code here
I hope it will help you resolve the problem.
You need to list the directory using the path to the directory not the url. Once you retrieve the files you must create your own html to put it your web if that's what you want.
There is a good example to create a directory listing and browsing with JQuery here
There is a JSP connector included in the package in the download section that you may need to tune up a bit if you don't want to use the JQuery tree.
good luck!
The HTTP protocol does not provide a way to list the "files" in a "directory". Indeed, from the perspective of the protocol spec, there is no such thing as a directory.
If the webserver you are trying to access supports WebDAV, you could use PROPFIND to find out a collection (i.e. directory)'s structure.
Alternatively, if the webserver has directory listing enabled (and there is no index.html or whatever) then you could screen-scrape the listing HTML.
Otherwise, there is no real solution ... using HTTP / HTTPS.
On rereading the question and the answers, it strikes me that the servlet that is trying to retrieve the directory listing and the servlet that hosts the directories could actually be running on the same machine. In that case, you may have the option of accessing the information via the file system. But this will entail the "client" servlet knowing how the "server" servlet represents things. The URLs don't (and cannot) provide you that information.
The answer provided by rickz is one possible approach, though it only works if the client and server servlets are in fact the same servlet.
Is it possible upload file through jsp.
var filepathhere = "http:// xxxx.com/--------/upliaded.pdf".
for exm: http:// xxxxx/test.jsp?file = filepathhere.
can i uses like this, is it possible to by using the path we can upload this.
Accept URL from user in HTML form.
POST URL to servlet , try to read File from passed URL check its type and other validations.
Read file from that URL and on write or insert it in to your own DB
File Upload and Download using Java
Yes you can. request.getParameter("file") return Object that you can cast it to String and can download from that URL
something like that :
String file= (String) request.getParameter("file");
URL fileUrl = new URL(file);
and can download from here
You can get the information in the format of string doing it this way but I don't think you can get any other format( like pdf in your example) of data directly from the url. You can off course first download the file to some path and then get it from there.