Reputation: 3698
I am trying to make a servlet to upload a file to a temporary location. When I build the file path everything seems alright.
String uploadFilePath = System.getProperty("java.io.tmpdir") + File.separator + UPLOAD_DIR;
and I get the absolute path: C:\Users\victor\AppData\Local\Temp\uploads
but when I call
part.write(uploadFilePath + File.separator + fileName);
I get: C:\Users\victor\GlassFish_Server\glassfish\domains\domain\generated\jsp\pcpweb\ C:\Users\victor\AppData\Local\Temp\uploads
and an java.io.FileNotFoundException afterwards, far enough I guess.
So "write" is completing my path. I there a way to avoid this? Thanks.
Using: glassfish and netbeans
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// constructs path of the directory to save uploaded file
String uploadFilePath = System.getProperty("java.io.tmpdir") + File.separator + UPLOAD_DIR;
// creates the save directory if it does not exists
File fileSaveDir = new File(uploadFilePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());
String fileName = null;
//Get all the parts from request and write it to the file on server
for (Part part : request.getParts()) {
fileName = getFileName(part);
part.write(uploadFilePath + File.separator + fileName);
}
request.setAttribute("message", fileName + " File uploaded successfully!");
getServletContext().getRequestDispatcher("gerencia.jsp").forward(
request, response);
}
Upvotes: 0
Views: 3992
Reputation: 22451
The javadoc for Part.write()
mentions that:
The file is created relative to the location as specified in the MultipartConfig
My understanding is that for Glassfish, if you don't specify the location, it defaults to the value of:
getServletContext().getAttribute("javax.servlet.context.tempdir")
Which is probably the extra path that you see.
Try specifying the location in the @MultipartConfig
annotation, e.g.:
@MultipartConfig(location="/somepath")
You could set the location to the value of the temp dir, and then just pass the bare filename to the write()
method.
Upvotes: 1