display byte array as image in angular js - javascript

I have an image in database. I want to retreive the image and display it in web page using angular js. After fetching data i have byte array. How do i send the data to the html page. I am having issues with the below code.. Kindly help.
When i click the link to view the image, page is sending 2 get requests to the server instead of one. It is sending request continuously for 2 times.
Note : I have tried using the below link.. But it didn't work
AngularJS - Show byte array content as image
Below is my js file
app.controller('aboutCtrl', function($scope,$http,$location) {
$scope.message = 'This is Add new order screen';
var url = '/Angular/login';
$http.get(url).success(function(result) {
$scope.image = result.image;
})
});
//html
<img data-ng-src="data:image/PNG;base64,{{image}}">
Java class file
public String getImage() throws FileNotFoundException{
String byteStr=null;
try
{
Connection con= DbConnect.getConnection();
String sql ="select * from image_data where id=1";
PreparedStatement ps=con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
Blob b=rs.getBlob(2);
byte barr[]=b.getBytes(1,(int)b.length());
byteStr = new String(barr);
}
}catch(Exception e){
e.printStackTrace();
}
return byteStr;
}
Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("inside get");
JSONObject result= new JSONObject();
Retreive rt = new Retreive();
result.put("image", rt.getImage());
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.write(result.toString());
out.flush();
out.close();
}

Seems like your image is not base64 encoded string but still that byte array. You need to encoded it first in order to use it like this <img data-ng-src="data:image/PNG;base64,{{image}}">
Check the documentation AngularJS - Show byte array content as image
You can also try this approach https://gist.github.com/jonleighton/958841

Related

How to display and interact with OKHTTP html response in android Studio using webview or Web browser

I am building an android app. I have build a request using OKHTTP and I get the response as a string composed of html css and js content. This response is actualy a form that the user must use to allow the app to communicate with a given website.
Now I want the user to be able to see that response as an html page and clicks on a button to allow the communictaion. Only problem I don't know how to display that response as an html in webview or in the web browser.
From the MainActivity:
Authenticate myAouth = new Authenticate("myCostumerKey","mySecretKey");
try {
myResponse=myAouth.run("myUrlHere");
//System.out.println( myResponse);
} catch (Exception e) {
e.printStackTrace();
}
the Autheticate class
public class Authenticate {
private final OkHttpClient client;
String[] myResponse =new String[2];
public Authenticate( final String consumerKey, final String consumerSecret) {
client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws IOException {
if (response.request().header("Authorization") != null) {
return null; // Give up, we've already attempted to authenticate.
}
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic(consumerKey, consumerSecret);
Request myRequest =response.request().newBuilder()
.header("Authorization", credential)
.build();
HttpUrl myURL = myRequest.url();
myResponse[0]= String.valueOf(myURL);
return myRequest;
}
})
.build();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public String[] run(String url) throws Exception {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
myResponse[1]=response.body().string();
System.out.println(" URL is "+myResponse[0]+" my response body is "+myResponse[1]);
}
return myResponse;
}}
Any help would be apriciated.
Kind Regards
You can use the following code to convert the String to HTML and then display it in a WebView
try {
String html = new String(response, "UTF-8");
String mime = "text/html";
String encoding = "utf-8";
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

How to send canvas png image to java servlet using ajax?

I am trying to send a canvas PNG to a java servlet using ajax.
Here is my javascript code:
function sendToServer(image){
$.ajax({
type: "POST",
url: "SaveAnnotation",
data: {
annotationImage: image
},
success: function(msg)
{
alert(msg);
},
error: function()
{
alert("Error connecting to server!");
}
});
}
function save() {
var dataURL = canvas.toDataURL();
sendToServer(dataURL);
}
And the java servlet doPost():
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
try{
String img64 = request.getParameter("annotationImage");
byte[] decodedBytes = DatatypeConverter.parseBase64Binary(img64);
BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));
File outputfile = new File("saved_annotations/saved.png");
ImageIO.write(bfi , "png", outputfile);
bfi.flush();
out.print("Success!");
}catch(IOException e){
out.print(e.getMessage());
}
}
The problem is that getParameter("annotationImage") returns null, and I can't understand why: using browser debugger I can see annotationImageand its value between the request parameters, so I am sure it is not null, but for some reason the parameter is not received by the Java Servlet.
I found out the reasons why it didn't work.
To avoid parsing JSON I send the data to the server without setting any parameter, writing data: image instead of JSON formatted data: {annotationImage: image} to avoid JSON parsing in the servlet.
In the java servlet I get the entire request body, remove the content-type declaration and finally decode and save the image. Here is the code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
StringBuffer jb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
String img64 = jb.toString();
//check if the image is really a base64 png, maybe a bit hard-coded
if(img64 != null && img64.startsWith("data:image/png;base64,")){
//Remove Content-type declaration
img64 = img64.substring(img64.indexOf(',') + 1);
}else{
response.setStatus(403);
out.print("Formato immagine non corretto!");
return;
}
try{
InputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(img64.getBytes()));
BufferedImage bfi = ImageIO.read(stream);
String path = getServletConfig().getServletContext().getRealPath("saved_annotations/saved.png");
File outputfile = new File(path);
outputfile.createNewFile();
ImageIO.write(bfi , "png", outputfile);
bfi.flush();
response.setStatus(200);
out.print("L'immagine e' stata salvata con successo!");
}catch(IOException e){
e.printStackTrace();
response.setStatus(500);
out.print("Errore durante il salvataggio dell'immagine: " + e.getMessage());
}
}

Jquery ajax request to server returning error code 405 on live server?

The following code is working fine when I run the application on localhost but it is not working when hosted on the live server, as the ajax request returned a error code
405 HTTP method get is not supported by this url.
I have making a get request and also handling this request in doGet method then what went wrong when I try to run this code on live server.
NOTE: only posting the required code js code
Client side code
$.ajax({
type:"GET",
url:"fetchdata1",
data:"cat="+cat,
success:function(data){
}
});
server side code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String cat = request.getParameter("cat");
PrintWriter out= response.getWriter();
ArrayList<product> p = new ArrayList();
try {
con=ConnectionManager.getConnection();
ps = con.prepareStatement("Select product_id,images.product_name,image_name,company_name,price "
+ "from images,products where images.product_name = products.product_name AND "
+ "category_name = ?");
ps.setString(1,cat);
rs=ps.executeQuery();
while(rs.next())
{
product pr =new product();
pr.id = rs.getInt("product_id");
pr.name = rs.getString("product_name");
pr.company =rs.getString("company_name");
pr.image = rs.getString("image_name");
pr.price = rs.getDouble("price");
p.add(pr);
}
String json = new Gson().toJson(p);
response.setContentType("application/json");
out.println(json);
}

HTMLUnit not working with Ajax/Javascript

I am trying to extract data for a class project from a webpage (a page that shows search results). Specifically, it's this page:
http://www.target.com/c/xbox-one-games-video/-/N-55krw#navigation=true&category=55krw&searchTerm=&view_type=medium&sort_by=bestselling&faceted_value=&offset=60&pageCount=60&response_group=Items&isLeaf=true&parent_category_id=55kug&custom_price=false&min_price=from&max_price=to
I just want to extract the titles of the products.
I'm using the following code:
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
final HtmlPage page = webClient.getPage(itemPageURL);
int tries = 20; // Amount of tries to avoid infinite loop
while (tries > 0) {
tries--;
synchronized(page) {
page.wait(2000); // How often to check
}
}
int numThreads = webClient.waitForBackgroundJavaScript(1000000l);
PrintWriter pw = new PrintWriter("test-target-search.txt");
pw.println(page.asXml());
pw.close();
The page that results does not have the product information that's shown on the web browser. I imagine the AJAX calls haven't completed? (not sure though.)
Any help would greatly be appreciated. Thanks!
You can use GET requests for such task. Control the page by the "pageCount" and "offset" argument in the URL, after retrieving the page (the example below does this for one page) you can use regex or whatever the content is in (JSON?) to extract the titles.
public static void main(String[] args)
{
try
{
WebClient webClient = new WebClient();
URL url = new URL(
"http://tws.target.com/searchservice/item/search_results/v1/by_keyword?callback=getPlpResponse&navigation=true&category=55krw&searchTerm=&view_type=medium&sort_by=bestselling&faceted_value=&offset=60&pageCount=60&response_group=Items&isLeaf=true&parent_category_id=55kug&custom_price=false&min_price=from&max_price=to");
WebRequest requestSettings = new WebRequest(url, HttpMethod.GET);
requestSettings.setAdditionalHeader("Accept", "*/*");
requestSettings.setAdditionalHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
requestSettings.setAdditionalHeader("Referer", "http://www.target.com/c/xbox-one-games-video/-/N-55krw");
requestSettings.setAdditionalHeader("Accept-Language", "en-US,en;q=0.8");
requestSettings.setAdditionalHeader("Accept-Encoding", "gzip,deflate,sdch");
requestSettings.setAdditionalHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
Page page = webClient.getPage(requestSettings);
System.out.println(page.getWebResponse().getContentAsString());
}
catch (Exception e)
{
e.printStackTrace();
}
}

Create application based on Website

I searched and tried a lot to develop an application which uses the content of a Website. I just saw the StackExchange app, which looks like I want to develop my application. The difference between web and application is here:
Browser:
App:
As you can see, there are some differences between the Browser and the App.
I hope somebody knows how to create an app like that, because after hours of searching I just found the solution of using a simple WebView (which is just a 1:1 like the browser) or to use Javascript in the app to remove some content (which is actually a bit buggy...).
To repeat: the point is, I want to get the content of a website (on start of the app) and to put it inside my application.
Cheers.
What you want to do is to scrape the websites in question by getting their html code and sorting it using some form of logic - I recomend xPath for this. then you can implement this data into some nice native interface.
You need however to be very aware that the data you get is not allways formated the way you want so all of your algorithems have to be very flexible.
the proccess can be cut into steps like this
retrive data from website (DefaultHttpClient and AsyncTask)
analyse and retrive relevant data (your relevant algorithm)
show data to user (Your interface implementation)
UPDATE
Bellow is some example code to fetch some data of a website it implements html-cleaner libary and you will need to implement this in your project.
class GetStationsClass extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "iso-8859-1");
HttpPost httppost = new HttpPost("http://ntlive.dk/rt/route?id=786");
httppost.setHeader("Accept-Charset", "iso-8859-1, unicode-1-1;q=0.8");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
String data = "";
if (status != HttpStatus.SC_OK) {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
response.getEntity().writeTo(ostream);
data = ostream.toString();
} else {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
"iso-8859-1"));
String line = null;
while ((line = reader.readLine()) != null) {
data += line;
}
XPath xpath = XPathFactory.newInstance().newXPath();
try {
Document document = readDocument(data);
NodeList nodes = (NodeList) xpath.evaluate("//*[#id=\"container\"]/ul/li", document,
XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Node thisNode = nodes.item(i);
Log.v("",thisNode.getTextContent().trim);
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//update user interface here
}
}
private Document readDocument(String content) {
Long timeStart = new Date().getTime();
TagNode tagNode = new HtmlCleaner().clean(content);
Document doc = null;
try {
doc = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
return doc;
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
to run the code above use
new getStationsClass.execute();

Categories

Resources