Sending images to angular client in spring boot rest api? - java

I am developing a rest api using spring boot.
I have an upload image service which stores images in my project workspace and image url in stored in db.
I have an entity product which has a list of images. Now I have to return images back to the angular client.
I have two questions in mind:
Q1. Should I return just a list of image urls to the client? If yes how should client render images from those urls.
Q2. OR Should I return list of images itself? If yes please show me logic which is fast and efficient.
Q3. OR Should I return individual image one by one? If yes please tell me how.
Update:
Note: Since, Rest api is on one machine and Angular client is on another machine. I think that the image url needs some kind of prefix:
Suppose my project is in E:/myproject/ and images are in E:/myproject/images/image-name.jpg, so what should be prefix for image url.

Q1. Should I return just a list of image urls to the client? If yes how should client render images from those urls.
THIS. Since all you need to do next is to give those urls <img src="something.png" /> tags in the front end. This will also free the server from the responsibility of downloading the image and service it to the clients.
Q2. OR Should I return list of images itself? If yes please show me logic which is fast and efficient.
This is possible but very hard. I don't advise doing this since this will make the system download the image twice: first is from file storage to the backend, then 2nd is from backend to frontend.
Q3. OR Should I return individual image one by one? If yes please tell me how.
This is the approach you need to do if the images needs individual security when downloading. Securing your image downloads is possible with the 1st approach that you given, and again, this approach will make you download the image twice.

Q1. Should I return just a list of image urls to the client? If yes how should client render images from those urls.
Ans : Return the list of urls to angular . Angular will use this code.
<div *ngFor="let image of images">
<img src={{image.ImagePath}} />
</div>
It will automatically fetch the images present at the url path

private static final Map<String, MediaType> TYPE_MAP = new HashMap();
static {
TYPE_MAP.put("pdf", MediaType.APPLICATION_PDF);
TYPE_MAP.put("gif", MediaType.IMAGE_GIF);
TYPE_MAP.put("jpg", MediaType.IMAGE_JPEG);
TYPE_MAP.put("jpeg", MediaType.IMAGE_JPEG);
TYPE_MAP.put("png", MediaType.IMAGE_PNG);
TYPE_MAP.put("html", MediaType.TEXT_HTML);
TYPE_MAP.put("xls", MediaType.parseMediaType("application/vnd.ms-excel"));
TYPE_MAP.put("xlsx", MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
}
#GetMapping(value = "/preview")
public ResponseEntity<Resource> previewFile(#RequestParam String filePath) {
Resource resource = new UrlResource(Paths.get(filePath).toUri());
String fileName = testFile.png;
String extension = png;
MediaType mediaType = TYPE_MAP.getOrDefault(extension,MediaType.APPLICATION_OCTET_STREAM);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "filename=\"" + fileName + "\"")
.contentType(mediaType)
.body(file);
}
Send filePath to the angular client and use this service in order to preview that file.

Related

How to read dynamic website content in java

As per the html the source code is:
{result.data}
While requesting the URL result.data is set with 100 and am able to see the value as 100 in the browser. Where as while I am trying to execute the java program with the same url request I am unable to see the value as I have seen in browser.
URL url = new URL(site)
url.openConnection() etc..
I wanted to get the same content as I have seen in the browser through java program.
Your question is not very descriptive, but I guess you are trying to scrape data from the site.
You can use the following libraries for this task:
Jaunt (http://jaunt-api.com)
Jsoup (http://jsoup.org/cookbook/extracting-data/dom-navigation)
HTMLUnit
To what i understand, you want to do one of the below things :
Instead of reading the result line by line, you want to parse it as an XML to as to traverse to div(s) and other html tags.
For this purpose i would suggest you to use jsoup library.
When you hit the URL: www.abcd.com/number=500 in browser, it loads an empty div and on load it fetches data from somewhere, this data which it fetches on load, you want to fetch this using java ?
For this, there must be some js in the resulting page, which is fetching data by hitting some service on page load, you will need to look up in the page to know the service details and instead of hitting this URL (www.abcd.com/number=500) you will need to hit that service to get data.

Freemarker embed image on ftl

I am trying to embed an image on a Freemarker ftl template to send as an email, I've based on this question Feemarker writing images to html, I did the exact same thing as this question said, but the email is being generated like this
What may be causing this error, and how to fix it?
My template looks like this
<img alt="My image" src="${imgAsBase64}" />
The image is a Chart, and I get the Base64 String, which I called imageBase64Str, via a Primefaces JavaScript function that generates the Base64 of the chart image, I pass it to the the bean and pass the parameter to the template like this
String encoded = imageBase64Str.split(",")[1];
byte[] decoded = Base64.decodeBase64(encoded);
String imgDataAsBase64 = new String(decoded);
String imgAsBase64 = "data:image/png;base64," + imgDataAsBase64;
emailParams.put("imgAsBase64", imgAsBase64);
String encoded = imageBase64Str.split(",")[1]; is suspicious. Looks like you are changing the base 64 string generated in some different way. Is the image actually a png or it's in another format? I think that if you remove that split and just do emailParams.put("imgAsBase64", imageBase64Str); it may work.
However you need to consider that this solution won't work for many email clients. According to this link https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/ Base64 embedded images are not supported on a few major email clients, web and standalone, including Gmail and Outlook. Given that they are the most common email clients you don't want to deliver a solution that doesn't work on them or most of your users are gonna be unhappy.
IMO your best bet is to host the images in a server and use fully qualified URLs in your freemarker template.
An alternative is using the attachment and reference them in the html source as explained here: https://stackoverflow.com/a/36870709/2546299 but it require changes on the way the emails are sent (need to add the attachments) so it may not be suitable for your case.

Handle file upload in RFC 6902 Json Patch

I'm working on a application in which users can update their information. For the moment, RFC 6902 Json-patch is used to update textual information (firstname, lastname, phone...) via a basic HTML Form.
User can now add images to their profile. Is there any way to use Json-patch to perform multipart operations ?
Note : The images are stored in a file system. So in the client side, only the image path is given and it can be updated only after the form submission. My dto is as below :
public class ProfileDto {
private Integer id;
private String firstname;
private String lastname;
private String defaultMedia; // <-- image path
...
}
Solution to which I think :
Since defaultMedia is of type String, Json-patch can be used to update the image path. The idea is when the form is submitted, perform a Multipart POST request to upload the image and get its URL. Then set defaultMedia of my DTO to the new URL.
This solution can create unsued images in the case when a error happened server side on form submission. So I need to add something to clean the file system.
Is there any easier solution to meet my needs ?
I'm using :
Spring Boot : 1.5.1
Angular 2 : 2.4.5

how can i send image object from php to Java webservice

I need a suggestion. Iam developing the face recognistion webservice (SOAP) in java, but front end is php application. User will send the image either by capturing using webcam or uploading the image. But i want this image and its detials as File Object in xml instead path from the server or database. Please suggest me how can i handle this or any other approaches.
Look at one of these:
$requestImageXML = '<img src="data:image/jpeg;base64,' . base64_encode(readfile($filePath)) . '"/>';
$requestImageString = base64_encode(readfile($filePath));
and use the string in a relevant way.

how to encapsulate a URL site into a Java object?

I hava a Java/Grails app that needs to "read" the contents of a given URL to use it as an image, mostly to be dinamically resized.
My app already parses the url into HTML code using an implementation based on this post: http://www.roseindia.net/java/example/java/io/SourceViewer.shtml.
The class I built returns a String object that contains the HTML source code. Now I want to write this String into an object similar to a BufferedImage so I can display the captured URL into my new application.
any ideas, thanks in advance!
You can use a service like Bluga.net WebThumb and use Glen Smith's ThumbnailService to interface with it.
Or, if you really want to do this by yourself, you can use his Thumbnail Server (with an older version of the ThumbnailService), that he used to use before migrating to WebThumb ;)
Regards
You can create an Image object from a url :
URL url = new URL("http://url.to/your/image.jpg";
Image image = Toolkit.getDefaultToolkit().createImage(url)
If by
take a 'print screen' of the this site
you mean display in your app take a look at this : http://www.java-tips.org/java-se-tips/javax.swing/how-to-display-pages-for-a-web-site-in-your-applic.html

Categories