Q:
How to save a blob to the server in java?
I am saving a blob to the server and that blob is a png image.
Code:
OutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "png", out);
String filePath = "c:\\upload\\" + (Long.toString(index));
Files.write(Paths.get(filePath), new ByteArrayInputStream(out.toByteArray()));
This gives me a file. It is a correct png image but when I try to retrieve that file then the browser is giving me an error:
Response Code:404
Requested URL :http://localhost:8080/app/upload/0
Severity: Error
Message:java.io.FileNotFoundException: http://localhost:8080/app/upload/0
But in my index page there is a link for upload image:
In my log file:
But I don't know why it is showing a page not found error.
Please help me.
Thanks
A:
You don't need to specify context path in img src attribute like:
src="<%=request.getContextPath()%>/upload/0.png"
Just pass whole path
src="upload/0.png"
Also you don't need Files.write method to write stream to local file. You can just do
Files.write(Paths.get(filePath), out);
So, complete code:
//write
OutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "png", out);
String filePath = "c:\\upload\\" + (Long.toString(index));
Files.write(Paths.get(filePath), new ByteArrayInputStream(out.toByteArray()));
//read
Blob imageData = Files.read(Paths.get(filePath));
System.out.println(imageData.length());
System.out.println(imageData.getContentType());
System.out.println(imageData.getMimeType());
System.out.println(imageData.getLength());
System.out.println(imageData.getFileName());
System.out.println(imageData.getContentLength());
System.out.println(imageData.getType());
System.out.println(imageData.getMimeType());
System.out.println(imageData.length());
System.out.println(imageData.length());
Here is output:
14471276
image/png
image/png
14471276
image/png
image/png
14471276
image/png
It looks like browser can't load the image or your image data is not present.
BTW, if you'll set correct url in img, you will see that the image is not found for download, because url can't be found by default in web browser
A:
You are trying to retrieve a file which is not present. If you are using the file name for the browser then it tries to find a file with the given name but finds none.
The best approach is to use URIs which provide a correct path:
" style="margin-left:5px; padding-left:5px;" />
Or URL encoding for those who do not use any frameworks.