Larsen Larsen - 6 months ago 10
MySQL Question

Showing LongBlob photos from MySQL on View by using Angular

Purpose: show different images on my html page by using Angular and the same Servlet (images will change depending on request parameters[id])

Code explanation:


  • I Stored some photos I want to show on my view on MySQL as longBlob

  • I send request to the Servlet by passing id=13 as params (see JS
    code)

  • Servlet will retrieve the photo stored in the DB having id=13

  • The response value will be passed to the variable "image" on $scope



Problem: The image doesn't appear on my view.

Error Chrome console:
http://localhost:8080/MyProject/%7B%7Bimage%7D%7D 404 (Not Found)

Console.log(response) result:
Object {data: "����..., status:200, config:Object, statusText:"OK"}

Additional info:


  • If I change "id" assignment from
    "=Integer.parseInt(request.getParameter("id"));" to "13" inside the
    Servlet, my image is properly shown on the Servlet URL, which means that the file is well retrieved and encoded.

  • If I add System.out.println(id) after "int
    id=Integer.parseInt(request.getParameter("id"));" it will be shown 13
    as value, which means params are correctly passed from JS file to Servlet.



-

MY HTML CODE:
...
<img class="images" src="{{image}}"/>
...


-

MY ANGULAR JS CODE:

...
$http.get('./ImagesServlet', {params: {id:13}})
.then(function(response) {
console.log(response)
$scope.image = response.data;
});
...


-

ImagesServlet CODE:
...
int id = Integer.parseInt(request.getParameter("id"));
PoiDao fetcher = new PoiDao();
try {
List<PoiImg> image = fetcher.ImgById(id);
response.setContentType("image/png");
Blob img = image.get(0).getPhoto();
InputStream in = img.getBinaryStream();
int length = (int) img.length();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
response.getOutputStream().write(buffer, 0, length);
}

} catch (ClassNotFoundException | SQLException e1) {
e1.printStackTrace();
}
...

Answer

JavaScript

If you don't want to change your $http call to expect a Blob directly,

let blob = new Blob([response.data], {type: 'image/jpeg'});

Otherwise, pass responseType: 'blob' into it so response.data will start as a Blob


Then convert this to a URL you can access from the HTML page

let url = URL.createObjectURL(blob); // note this will prevent GC of blob

Finally if you want to be clean, when you're done with this image

URL.revokeObjectURL(url); // frees blob to be GCd
Comments