Reputation: 2143
I am currently working on a web application. In some part of this application I want to upload files to a certain directory. Initially, when I wrote my test cases this worked perfectly:
final static String IMAGE_RESOURCE_PATH = "res/images";
...
File directory = new File(IMAGE_RESOURCE_PATH + "/" + productId);
if(!directory.exists()) {
directory.mkdirs();
}
This creates the directory wherein the file will be uploaded. The resulting path will be:
[project root folder]/res/images/[productId]
Since deploying the application to a server (Tomcat 7), the directory gets created in the root of the IDE I'm using, which is a bit confusing to me.
eg: C:\Eclipse86\res\images
Any idea how I can revert back to the project path with just plain Java without using some hacked technique or hard-coding the path?
Upvotes: 1
Views: 13647
Reputation: 3088
Some years ago I wrote a servlet that DOWNloads a file. You could quickly refactor it for uploading. Here you go:
public class ServletDownload extends HttpServlet {
private static final int BYTES_DOWNLOAD = 1024;
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("/downloadme.txt");
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
}
Also, there is an easy way to get the projects' path, as new File().getAbsolutePath().
Upvotes: 1
Reputation: 2673
If you don't specify the absolute path, your directory will be created inside (or, if correctly, relative to) working directory of the application.
If you want to get directory inside your web application you should use getServletContext().getRealPath(String path)
. For example, getServletContext().getRealPath("/")
is the path to the root directory of the application.
To create directory with path [project root folder]/res/images/[productId]
, do something like this:
// XXX Notice the slash before "res"
final static String IMAGE_RESOURCE_PATH = "/res/images";
...
String directoryPath =
getServletContext().getRealPath(IMAGE_RESOURCE_PATH + "/" + productId)
File directory = new File(directoryPath);
if(!directory.exists()) {
directory.mkdirs();
}
Upvotes: 5