I have a .jsp page that show a file browser and a upload button and a Servlet that should upload the file to server . The problem is that the file is uploaded to a temporary folder but I need it to be uploaded on a specific path on the server, but the path isn`t recognized.
UploadServlet: the doPost method
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// get access to file that is uploaded from client
Part p1 = request.getPart("file");
InputStream is = p1.getInputStream();
String filename = getFilename(p1);
// get temporary path - this works but it saves on a tmp folder...
//String outputfile = this.getServletContext().getRealPath(filename); // get path on the server
//hardcoded path on which I have to save my file
String outputfile = "http://localhost:8080/Tutorial2/Upload/" + filename;
FileOutputStream os = new FileOutputStream (outputfile);
// write bytes taken from uploaded file to target file
int ch = is.read();
while (ch != -1) {
os.write(ch);
ch = is.read();
}
os.close();
out.println("<h3>File uploaded successfully!</h3>");
}
catch(Exception ex) {
out.println("Exception -->" + ex.getMessage());
}
finally {
out.close();
}
}
private static String getFilename(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
The .jsp page
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Select File : </td>
<td><input name="file" type="file"/> </td>
</tr>
</table>
<p/>
<input type="submit" value="Upload File"/>
</form>
I've seen many posts on this matter but neither helped me. When i run my servlet i get an exception at FileOutputStream os = new FileOutputStream (outputfile);
- Exception -->http:\localhost:8080\Tutorial2\Upload\SvnBridge.exe (The filename, directory name, or volume label syntax is incorrect)
. Searched for this and didn't find anything relevant. I don't know if it helps but I use Servlet 3.0 and Apache Tomcat v7.
Do you have any ideea why can`t I write my file to the path above?
Thx,