I want to upload the files into mysql database using jsp.When i use input type=”file”, jsp is not returning full path. i need full path to upload a file in mysql db.
<form id="translationFormID" method="post" action="saveTranslation">
<input type="file" name="attachCV" id="attachCVID" value="Attach CV">
<input type="submit" name="submit" />
</form>
This is my jsp page. i calling the servlet ‘saveTranslation’ using post method.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String attachCV=null;
try{
String attachCV=request.getParameter("attachCV");
System.out.println("path= "+attachCV);
}
catch(Exception){
e.printStackTrace();
}
}
This is my servlet code. here getting and printing attachCV parameter. when i print the attachCV, its showing something like ‘c:\fakepath\sample.docx’
There’s a major thinking mistake here.
Imagine that I am the client who want to upload the file and that you are the server who need to get the file’s contents. I give you my full local disk file system path
c:\path\to\sample.docxas the sole information, exactly as you requested. How would you as being the server ever get its contents? Do you have an open TCP/IP connection to my local hard disk file system? Really?This isn’t how uploading files works. This would only ever work if the server runs at physically the same machine as the client, so that you can just use
FileInputStreamwith that path. This would thus only ever work in the local development environment, but definitely not in real world production where the server runs at a physically different machine than the client, separated by a HTTP connection.You should instead be interested in the sole file contents which the client has sent to you along with the HTTP request body. In HTML terms, you can use
<input type="file">for this in a<form enctype="multipart/form-data">. A more detailed answer with full code examples can be found here: How to upload files to server using JSP/Servlet? It describes the modern Servlet 3.0 way usingrequest.getPart()and the previously defacto standard Apache Commons FileUpload API.Once you’ve implemented it the right way, you should ultimately end up with an
InputStreamrepresenting the file contents which you obtained from the Servlet 3.0part.getInputStream()or the Apache Commons FileUploaditem.getInputStream(). You can then just usePreparedStatement#setBinaryStream()the usual way to store it in the DB andResultSet#getBinaryStream()to retrieve it from the DB.