Javascript/html - File upload - java

I have a news section where I can post some news.
-> Thumbnail , title and content
What I want:
The user should be able to upload an image file without leaving the page
-> progress bar
Send the file as a post request to my server.
Then I can get the image file from the post request, then I can resize/rename the image and upload it to amazon s3.
If I have to use a javascript library, I would prefere to use jquery.
This should looks something like this:
If I submit the news, I want to save the image path in my database. Now I would need a way to get the image name from my post method.
I've found some uploading solutions, but I have problems to understand how they are working.
http://blueimp.github.com/jQuery-File-Upload/
http://www.uploadify.com/
I only know get/post to retrieve information but they integrate somehow php files in the form.
for example:
$(function() {
$('#file_upload').uploadify({
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php'
// Put your options here
});
});
I am lacking information to do this on my own. What would you recommend me?
Ps: I am using Java with Play2

Uploadify is definitely the way to go.
All the steps for implementation are to be found here : http://www.uploadify.com/documentation/uploadify/implementing-uploadify/
You need to configure the path where your uploads go in the uploadify.php script.
As for amazon S3 here is an implementation : http://code.google.com/p/uploadify-amazon-s3/
I think onUploadSuccess method better fits than onSelect : http://www.uploadify.com/documentation/uploadify/onuploadsuccess/

You can do something like this from the documentation :
$(function() {
$("#file_upload").uploadify({
'swf' : '/uploadify/uploadify.swf',
'uploader' : '/uploadify/uploadify.php',
'onSelect' : function(file) {
alert('The file ' + file.name + ' was added to the queue.');
}
});
});
Where you can get the flename once it has been selected.

What you're asking for is a LOT really. But to get you started, have a look at this page (uses JQuery):
http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/
The above link is a nice upload utility that you can use for drag-and-drop pretty easily, but it can be used by manually selecting files as well. Well documented.
As for resizing, I've used this with great success (PHP): simpleImage
simpleImage is REALLY easy to use and plug into your website.

Related

Why is my Jsoup Code not Returning the Correct Elements?

I am working on an app in Android Studio and am having some trouble web-scraping with JSoup. I have successfully connected to the webpage and returned some basic elements to test the library, but now I cannot actually get the elements I need for my app.
I am trying to get a number of elements with the "data-at" attribute. The weird thing is, a few elements with the "data-at" attribute are returned, but not the ones I am looking for. For whatever reason my code is not extracting all of the elements that share the "data-at" attribute on the web page.
This is the URL of the webpage I am scraping:
https://express.liatoyotaofcolonie.com/inventory?f=dealer.name%3ALia%20Toyota%20of%20Colonie&f=submodel%3ACamry&f=trim%3ALE&f=year%3A2020
The method containing the web-scraping code:
#Override
protected String doInBackground(Void... params) {
String title = "";
Document doc;
Log.d(TAG, queryString.toString());
try {
doc = Jsoup.connect(queryString.toString()).get();
Elements content = doc.select("[data-at]");
for (Element e: content) {
Log.d(TAG, e.text());
}
} catch (IOException e) {
Log.e(TAG, e.toString());
}
return title;
}
The results in Logcat
The element I want to retrieve
One of the elements that is actually being retrieved
This is because some of the content - including the one you are looking for - is created asyncronously and is not present in initial DOM (Javascript ;))
When you view the source of the page you will notice that there is only 17 data-at occurences, while running document.querySelector("[data-at]") 29 nodes are returned.
What you are able to get in the JSoup is static content of the page (initial DOM). You wont be able to fetch dynamically created content as you do not run required JS scripts.
In order to overcome this, you will have to either fetch and parse required resources manually (eg trace what AJAX calls are made by the browser) or use headless browser setup. Selenium + headless Chrome should be enough.
Letter option will allow you to scrape ANY posible web application, including SPA apps, which is not possible using plaing Jsoup.
I don't quite know what to do about this, but I'm going to try one more time... The "Problematic Lines" in your code are these:
doc = Jsoup.connect(queryString.toString()).get();
Elements content = doc.select("[data-at]");
It is the queryString that you have requested - the URL points to a page that contains quite a bit of script code. When you load up a browser and click the button (or menu-option) that reads: "View Source", the HTML you see is not the same exact HTML that is broadcast to and received by JSoup.
If the HTML that is broadcast contains any <SCRIPT TYPE="text/javascript"> ... </SCRIPT> in it (and the named URL in your question does), AND those <SCRIPT> tags are involved in the initial loading of the page, then JSoup will not know anything about it... It only parses what it receives, it cannot process any dynamic content.
There are four ways that I know of to get the "Post Script Loaded" version of the HTML from a dynamic web-page, and I will type them here, now. The first is likely the most popular method (in Java) that I have heard about on Stack Overflow:
Selenium This Answer will show how the tool can run Java-Script. These are some Selenium Docs. And then there is this page right here has a great "first class" for using the tool to retrieve post-script processed HTML. Again, there is no way JSoup can retrieve HTML that is sent to the browser by script (JS/AJAX/Angular/React) since it just a parser.
Puppeteer This requires running a language called Node.js Perhaps calling a simple Node.js program from Java could work, but it would be a "Two Language" solution. I've never used it. Here is an answer that shows getting, sort of, what you are trying to get... The HTML after the script.
WebView Android Java Programmers have a popular class called "WebView" (documented here), that I have recently been told about (yesterday ... but it has been out for years) that will execute script in a browser, and return the HTML. Here is an answer that shows "JavaScript Injection" to retrieve DOM Tree elements from a "WebView" instance (which is how I was told it was done)
Splash My favorite tool, which I don't think anyone has heard of, but has been the simplest for me... So there is an A.P.I. called the "Splash API". Here is their explanation for a "Java-Script Rendering Service." Since this one I have been using... I'll post a code snippet that shows how "Splash Tool" can retrieve post-script processed HTML below.
To run the Splash API (only if you have access to the docker loading program) ... You start a Splash Server as below. These two lines are typed into a GCP (Google Cloud Platform) Shell instance, and the server starts right up without any configurations:
Pull the image:
$ sudo docker pull scrapinghub/splash
Start the container:
$ sudo docker run -it -p 8050:8050 --rm scrapinghub/splash
In your code, just prepend the String to your URL's:
"http://localhost:8050/render.html?url="
So in your code, you would use the following command (instead), and the script would (more likely) load all the HTML Elements that you are not finding:
String SPLASH_URL = "http://localhost:8050/render.html?url=";
doc = Jsoup.connect(SPLASH_URL + queryString.toString()).get();

Share text with picture to telegram

I want to create an app in Android and I want to share text with a picture to telegram but I do not want the pictures and the text to be separated. I don't know how to do this.
Hopefully it works fine, I tried same.
$.sendPhoto(image_url,{caption : 'i am attached text with image'});
//bot.sendPhoto(chatId,image_url,{caption : 'i am attached text with image'}); /* TRY these according to you.
Or, if you want to send it from Telegram rest api, then call this api:
API URL : 'https://api.telegram.org/bot'+token+'/sendPhoto?
chat_id='+chatID+'&photo='+imageSrc+'&caption='+(message ?message : '');
METHOD : GET

Vaadin FileDownloader: start download manually

I am building a project which downloads several PDF files from different URLs, merges them into a single one and downloads it.
I'm trying to use Vaadin's FileDownloader to achieve this:
final FileDownloader fileDownloader = new FileDownloader(new FileResource(resultResource.getFile()));
fileDownloader.extend(download);
The resultResource is the generated PDF which I want to download.
Now the problem is that it takes a short time to generate the PDF, so that sometimes the download happens before the new file is generated, resulting in it downloading the old file, or an empty one.
So what I've been trying to do is something like this:
download.addClickListener(e -> {
try {
// This creates the new PDF
pdfConverter.manipulatePdf(storeNumber.getValue());
fileDownloader.download();
} catch (...) {
...
}
});
But so far without any success. Is there any way to something like this? To disable the "automatic" download and trigger it manually?
There are two approaches you can try
First approach is to refactor your UI so, that PDF file is started to be generated when you enter the view, and once complete you enable the download button. You can have other indicators like progress bar if that is feasible.
In Vaadin 8.4+ you can also setup FileDownloader by extending EventTrigger (see pull request https://github.com/vaadin/framework/pull/10478 ) and API spec https://vaadin.com/download/release/8.4/8.4.2/docs/api/com/vaadin/server/EventTrigger.html That could be something to be exploited if the first way is not applicable for you.

Sending a String in Javascript to java method in Play Framework

I'm working on a system for my university and I'm using the play framework to do that.
The Admin of this system sets a marker on a google map and I get the coordinates from that point.
Now I'm trying to pass this information to the server side, so that I might store these to Strings in a mySQL database. The only problem I have is passing the data from my String in javascript/JQuery to the java function.
I tried different solutions on the internet but some of them seemed outdated and I couldn't figure out how to do it.
I've only been programming in Java, Javascript, JQuery and PHP and have never used AJAX (like the $.get() methode from JQuery), but I think it might be pretty similar to what I know from PHP.
e.g.
http://java.dzone.com/articles/jquery-ajax-play-2
I'd like to pass my String with a button click to my java function, so I can store it in my db.
I'm really confused about this.
I know I can use something like
<a href="{#routes.Application.postMethod()}"> Send </>
and then mention the function in the routes like
POST /post controllers.Application.post();
but how do I pass my qjuery string?
and how do I store my String as a String in a java function like:
public static Result post(String Lat, String Lng){
???????????? EVOLUTION NEEDED ?????
}
Thanks in advance I really need your help :)!
I don't see why you are doing a POST, since this can be done using a GET request.
As per this example:
http://www.playframework.com/documentation/1.2/ajax#jsaction
We can see Play makes it easier using the jsAction tag. Lets assume you have the following route:
GET /admins/marker Admins.marker
Then in your HTML, at the bottom you'd do something like:
<script type="text/javascript">
$('#myButton').click( function() {
var action = #{jsAction #marker(':latitude',':longitude') /}
$('#result').load(
action({latitude: '23', longitude: $('#longitudeField').val }),
function() {
$('#content').css('visibility', 'visible')
}
)
});
</script>
In this case, the request will be sent like (example):
GET /admins/marker?latitude=23&longitude=67
And then on your backend, you need the have to java fn to deal with that route.
Basically the javascript/jquery, is called when #myButton element is clicked, then we generate the route URL we are going to make a request to using jsAction, then we make using load to make a GET request. You can change this to post too if you'd like.

Playing SCORM on Android devices

I've got few questions about Android and SCORM. In both areas I'm pretty new and I only spent one evening digging the web in search of some answers.
Topics I found were about synchronizing SCORM package with LMS but I do not need that. I'm just wondering how to PLAY (and just play, no need for any syncing or tracking) SCORM package on android device (Lenovo tablet with Android 4+ OS). If I try to make my own application which allows to browse local SCORM packages, will I be able to launch SCORM by using WebView component?
I found this tutorial:
http://support.scorm.com/entries/21826060-RSOfflinePlayer-Developer-Tutorial
which has section:
Playing Content and Syncing Results
where I found some interesting source code about configuring this WebView component in order to play SCORM content, but I'm not really sure if I need RSOfflinePlayer.jar for this.
I've also heard, that if device supports Flash, I will be able to launch SCORMs with Browser - is it true?
Maybe you know some application which can do that? Or library which could help?
Is there anyone with experience in:
1) Java SCORM API:
would paste URL, but I need more reputation
2) Celine
https://code.google.com/p/celine-scorm/
Any help will be appreacieted, not only by me but also by children with different kinds of diseases (we are just students trying to help them).
Javier is almost right. I will nonetheless try to explain this again. Maybe you will gather more information from this.
Every SCO is basically a zipped webpage. You have to unzip it and look for imsmanifest.xml, find the initial file in there (index.html, player.html, something like this). It will NOT be located under resources. You first have to look at Organizations > Organization > Item > Identifierref, which will give you an ID. Then you have to look at Resources > Resource with the above ID > href value. This is the file you're looking for.
Example (index.html is the file you need):
<organizations default="someorg">
<organization identifier="someorg">
<title>Some Title</title>
<item identifier="CourseItem01" identifierref="SCO_Resource_01" isvisible="true">
<title>SCO Title Here</title>
</item>
</organization>
</organizations>
...
...
<resources>
<resource identifier="SCO_Resource_01" type="webcontent" adlcp:scormtype="sco" href="index.html">
<file href="index.html"/>
<file href="SCORM_API_wrapper.js"/>
...
Once you found it, just open it in WebView and it'll try to connect to SCORM API in the parent window. You'll have to provide some dummy functions to fool it into thinking that it did connect to LMS and carry on as usual. Otherwise it will either fail or throw alerts at you.
I don't have any Android experience, but I have some experience working with SCORM.
To play a SCORM object, you need to open the right file inside the right environment, the right file is stated in the imsmanifest.xml file, that will be always in the top level of the zip package, you have to look for something like this:
<resources>
<resource identifier="546468" type="webcontent" href="index.htm" adlcp:scormtype="sco">
<file href="index.htm" />
</resource>
</resources>
This means that you have to open index.htm in the top level, in general you have to look for the first resource with adlcp:scormtype="sco" (if you need more details, read the SCORM spec).
When this page loads, it will look for the API object, it must be in the parent window, or parent frame, you will need a dummy SCORM API, something like:
function ScormAPIClass()
{
this.GetLastError = function (){return 0};
this.GetErrorString = function (param){return ""};
this.GetDiagnostic = function (param){return ""};
this.SetValue = function (element, value){
//you need something else here
return true};
this.GetValue = this.SetValue = function (element){
//you need something else here
return true};
this.Initialize = function (param){return true};;
this.Terminate = function (param){return true};
this.Commit = function (param){return true};;
this.version = "1.0";
}
window.API_1484_11 = new ScormAPIClass();
The SCORM objects will assume that you API works, so, if the set and get functions are not real this can generates errores depending on the object logic.
Also, I did not tested the code, is only to give you an idea of what you need.
I hope this help you.
First you have to understand structure of Scorm.
You can see Scorm package is a zip file containing several folders right and a manifest file.
First you have to unzip that zip package of Scorm and then you have to parse that imsmanifest.xml file and maintain two lists one containing titles and other addresses of html files corresponding to that title.
I have used sax2r2 parser to parse that manifest file and got that two array lists one containing title and other addresses of html files.
Later you just have to fill up you IOS list with titles array, and when user click on any title of that list get the position of list and retrieve the address of html files corresponding to that title from addresses array list.
finally you can open html file in webview of your IOS, make sure have enabled parameters required for open scorm html5 file.
In android I have enabled and set these values this is java code but it may help you.
WebViewClient webViewClient = new WebViewClient();
webView.setWebViewClient(webViewClient);
webView.clearCache(true);
webView.getSettings().setUseWideViewPort(true);
webView.setInitialScale(1);
webView.getSettings().setBuiltInZoomControls(true);
webView.clearHistory();
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.loadUrl("file://" + open_scorm.scorm_path
+ open_scorm.scorm_name + "/" + open_scorm.href.get(0));
webView is used to open html/html5 files in android and i have enabled above settings in android, these settings are by default in android, may be in ios you just have to load that html file and dnt have to enable all these values.
In above you can see I am retrieving href.get(0) which is first html5 file of scorm.
In simple words you just have to unzip scorm , parse imsmanifest.xml file and get data of it and use it to open/parse scorm.

Categories