Sending an image to a online storage/database using XHR - javascript

I've been through a few similar posts here, but cannot seem to find what I need.
I have a web application (HTML5 and Javascript), which has a picture taking function and I need it to then send it to some form of storage or database (preferably something like .json). I am quite new to web development so I am not very familiar with how exactly this would work.
So far I have the following code, which takes the picture and sends it using XHR.
<input id="objPic" type="file" accept="image/*" capture="camera">
<script>
var newImage = document.getElementById('objPic');
function sendPic()
{
var file = fileInput.files[0];
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/path', true);
xhr.send(file);
}
myInput.addEventListener('change', sendPic, false);
</script>
My Question is about how/where to send it (what do I put as a path)? What is the best way to store the images?
My webpage is using github as a host (if that is relevant in any way).

Unfortunately this is not really easy. As you said you need to access some form of storage, and GitHub Pages (I imagine that's what you use) doesn't provide that. Depending on your needs I see two ways forward:
If you only need to store the image for the user who uploads it, you could save it directly in his browser using localstorage.
If you need to access the images of all users, you could use a javascript API of a third-party storage provider, like Google Cloud Storage. This is an example that can get you started.

Related

How to push data to external JSON file (Using jQuery)?

I want to push an data to array in external local JSON file using jQuery.
So any ideas?
I have tried this:
$.getJSON('test.json', function(data) {
data.push('Something');
});
And it wont be pushed into local JSON file
You can do this in JavaScript with node.js (or a multitude of other languages/platforms) but not with a browser & jQuery.
Here's how to read and write a json file in node.js
On the other hand, users could upload a JSON file to your server, where you modify the structure and send them a modified JSON file back as a download.
Is not possible to write files using Javascript (can cause security problems through xss, csrf ..)
No, JavaScript doesn't have access to writing files as this would be a huge
security risk to say the least. If you wanted to get/store information server-
side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc.
script that can then get/store the data in the server. If you meant store data
on the client machine, this is impossible with JavaScript alone. I suspect
Flash/Java may be able to, but I am not sure.
If you are only trying to store a small amount of information for an
unreliable
period of time regarding a specific user, I think you want cookies. I am not
sure from your question what you are trying to accomplish, though.
Read/write to file using jQuery
You cannot access the files in a local client's machine. May be for development setup you can do it. But before you need to restart the browser with file-access flag set.
You can see my answer here that describes the opening browser setup with the flag set.
Then, you can use the following code to read the data.
var data = [];
var url = "/Users/Vignesh/Desktop/test.json";
var req = new XMLHttpRequest();
req.open("GET",url,true);
req.onreadystatechange=function(){
if(req.readyState === 4)
{
data = JSON.parse(req.responseText);
}
};
req.send();
To write into the file you may look into this. (Not sure it is working or not)

Upload with JavaScript using Firebase Storage and Dropzone

I have been doing a lot of research and have yet to find a viable solution for the following. I asked a more specific question here) but due to the lack of answers or comments, I decided to ask a more generalized question that may be applicable to more people.
Anyway, dropzone.js allows you to create a file upload with js. Below is a snippet of code that does just that:
var myDropzone = new Dropzone(document.body, {
url: "/" // Not sure what to put here...
});
Where the url: "" would be equivalent to the action="" in a form. Most examples you can find have url: "upload.php" however I am trying to upload the images to firebase. Is there a way to run js for the file upload instead of php? perhaps url: "upload.js"? That wouldn't work but just to show what I mean. Or is there a way to upload images to Firebase with PHP? I am not quite sure how to proceed.
Here is what dropzone.js says about the URL attribute, I just don't understand it fully:
URL: Has to be specified on elements other than form (or when the
form doesn't have an action attribute). You can also provide a
function that will be called with files and must return the url (since
v3.12.0)
You can't upload directly to Firebase Storage via some special URL that you can put in a web form. But you can easily implement an endpoint with Cloud Functions for Firebase with a little extra code you write that runs on the server side.
I have a short Gist that gives all the code that makes it happen.
You can watch the code in action in this tweet.
I hosted my web site via Firebase Hosting, but if you don't do that, you may need to set up CORS or something to be able to call from your page to Cloud Functions.

Actual changing of XML file in Javascript / AJAX

since days I have been searching for answers but couldn't get what I am searching for.
I program a realtime webapp using Javascript and HTML5. For saving game stats I wanted to use a XML-file, that holds all the levelpoints and the achievements and lies locally within the same folder as the html.
So I found out, how to read out the values stored in the XML-file with an XMLHttpRequest. The problem is, that I can only change the node values client-sided, so if I empty the cache or simply reload the page, the XML does hold the original values.
To save the XML server-side is what I want. I hope, you can help me :)
Thanks in advanced!
You can use XMLHttpRequest (an AJAX request) to send the updated XML to the server and then have a server side script (using a server side language such as PHP for example) which will replace the contents of the XML file on the server.
Here's for example how you could send the XML to the server:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/some_script', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(this.responseText);
}
};
var xml = '<foo>Bar</foo>';
xhr.send(xml);
The apps that save game stats, store the data locally on the client. They don't post on to the server. If they are, then they would need internet connectivity and post data to the game server. where again there would be a PHP page or a servlet to handle data.
For client side storage, HTML5 has options. Please check the below link
http://diveintohtml5.info/storage.html

Canvas Image to an Image file

So i have a canvas on which the user signs, now instead of converting it to a base 64 string i simply want to save it as an image itslef. whats the easiest way to do it html5??
You can easily do that this way (specifying the format as png in this case):
var img = canvas.toDataURL("image/png");
You can specify different image formats.
Take a look at this answer.
I've answered a similar question here:
Simulating user event
Assuming you are saving locally
You can go the route of creating an image from a Data URL, but then saving it is the trickier part that currently isn't very nice using HTML5. It's hopefully going to get better soon, if browsers incorporate the download attribute of the a tag.
Obviously if you have higher permissions than a standard webpage... i.e. you are designing a browser plugin - then there are other options...
If I were to implement something like this myself, at the moment, I would conceed to using a flash plugin to handle the save to the local computer.
Assuming you are saving remotely
By the sounds of it you aren't saving to a server, but if so this is quite easy by just POSTing the base64 information to a script written in a server-side scripting language (i.e. like PHP) and getting that to write the data directly as binary to a file. Obviously you have to make certain you do this securely however, you don't want just any binary data written to your server's filesystem.
Best of both worlds
If you've got the development time, the best method to get a canvas image saved locally - without Flash - is to create a server-side script that instead of saving the data to your server actually writes the Base64 information you send it directly back as a realised binary image file. That way you can create a form that posts your Base64 data to a new tab, this request is evaluated by the server-side, and the binary image is returned... at which point the browser asks the user where they wish to save their image.
You'll need to define the correct headers to force an image to download (rather than display in-browser). A simple change to force this is to set the server-side script's Content-type header to 'image/octect-stream'... there are other header options to set which would be best researched (i.e. headers that control the filename and so forth).
reflect.php
<?php
/// a simple example..
if ( array_key_exists('data', $_POST) && ($data = $_POST['data']) ) {
header('Content-type: image/octet-stream');
echo base64_decode( $data );
exit;
}
and the form...
<form action="reflect.php" method="post" target="_blank">
<input name="data" type="hidden" value=" ... Base64 put here with JS ... ">
</form>
(The whole form should be created dynamically and submitted automatically with JavaScript)
Improving the user experience
There are ways to avoid a new tab being created, but you'd have to research to make sure these other methods don't cause cross-browser problems... for example you could post your form data as part of an iframe (which would keep the process hidden), or just post the data directly on the current window (..and hope that all the browsers receive the correct request and open a download rather than replace your page content - most modern browsers should handle this).
Improving security
With regards to a PHP script that automatically returns binary data, you should keep the access to this script secured by one time use key / authentication token or something similar, and keep a limit on how much Base64 data you are willing to accept. It might not seem like it poses a secutiry risk - as you are not modifying your server in any way with what the user sends - but the dodgy people of this world could take your script and use it to send download request to other users... which if downloaded (and turned out to be unwanted trojans or viruses) would make your server implicit in providing the dodgy file.
All in all
Due to the effort required to get a simple thing like an image saved to the desktop, I wouldn't blame you for doing the following:
Embed the image in the page (after taking your snapshot from canvas) and ask the user to right click and Save as...
Hopefully future things will make this situation better...

Best way to store temp data to pass from web application to desktop application using javascript

I'm looking for the best practice here.
I need to store 10 variables of information, in a certain format:
lname: [John]
fname: [Doe]
etc...
using Javascript. I was thinking about using cookies.
My scenario is as follows:
The user would be in Salesforce.com and they would enter the customer's information into a record. They would then click a button get a quote. The button, using JS, would write the Salesforce fields to a temp file (cookie maybe). From there the other MS application would pick up that file and read in the values.
How would you guys do that?
Thanks for the time.
The browser will not allow you to write files, generally speaking. For this, you'd have to use a mechanism to get out of the security sandbox, such as a signed Java applet.
Cookies are NOT a good option here. Desktop apps should not be attempting to access browser cookies; at best, it's considered "badly behaved code"; at worst, you won't be able to do it, or your app will get detected as malware. Even if it was considered OK, you'll have to write cookie-reading implementations for any browser you want to support since there is no standard for how they are locally stored.
Why not make the desktop app access the web on behalf of the user? Write SFDC quote requests to a new SFDC custom object, like Quote_Request__c or similar, and the app can query the most recent record(s) created by the user via the API.
Clipboard integration, while it sometimes seems clunky, may be a low-cost option.
If you must write to a local file of some sort, you'll need to use Flash or Java, or make the user locally save some downloaded file (like any normal browser download).
Another option would be to register your desktop app as a URL protocol handler; so, say, myquote://firstname/lastname/product/price/etc could be clicked from a web browser to launch the app and parse the "URL". May work poorly with very long/complicated data though.
Yes, cookies are certainly an option in this case. Cookies are accessible via the document global object (e.g. document.cookie). It can hold a string and an expiration date.
Here is a cookie handler I wrote:
http://jsfiddle.net/zbaJz/1/
Using this handler, you can store information in a cookie, and would be able to view as well as delete it. Then, using JSON stringify, you can pass it an object.
var name = {
'fname': 'John',
'lname': 'Doe'
};
var jsonText = JSON.stringify(name);
var cookieMonster = new Ovenmitts();
cookieMonster.bakeCookie('name', jsonText);
Then, in order to turn the data back into an object to manipulate, you would use JSON.parse.
var cookieInfo = cookieMonster.admireCookie('name');
var revived = JSON.parse(cookieInfo);
You can add a thread/task to the MS Application that watches for changes in the directory whee the cookie is created. When you detect a new file that meets your requirements you can act on it. You will need to use DirectoryInfo for this approach.
You can also create and windows or webservice that the application listen to and can pass the data this way from the web app.

Categories