I have looked around for the solution but cant find any solution.
I am storing a file in me local drive and storing path of that file in my mongoDB,
after retrieving the path I want to give URL the path from DB. When I click on that URL that path should opent that related file.
My codes are as
Data in db as:
"filePath" : "C:/myfiles/Resume_Vipul.docx"
accessing it in front end as:
<c:forEach var="ser" items="${services}" varStatus="status">
<td class="text-center"><a href='<spring:url value="${ser.filePath}" />'>file</a></td>
</c:forEach>
when I click on the Url it gives me error as:
Not allowed to load local resource: file:///C:/myfiles/Resume_Vipul.docx
What is the correct way of performing this action. any help would be appreciated.
You should send a request to the controller taking the file name as parameter and send back the bytes as response, something like this,
ServletContext cntx= req.getServletContext();
// Get the absolute path of the image
String filename = cntx.getRealPath("Images/button.png");
// retrieve mimeType dynamically
String mime = cntx.getMimeType(filename);
if (mime == null) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mime);
File file = new File(filename);
resp.setContentLength((int)file.length());
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
out.close();
in.close();
Accessing the local resources from the client side is I think not a good idea. Consider making a separate request for this to the server. In your case, you can send the resource path as String
parameter to the server.