How to upload an image file using only javascript and ajax - javascript

In form, There is a field of file
<input type="file" name="file">
<input type="button" value="upload">
I want to upload image file onto server but I can't able to upload the image. Is there any solution in only javascript? Please help me to find this answer.
Thanks..!

This isn't possible with JavaScript alone, you will need to use a server side language to process the actual uploading of the file.

This will do the job in Firefox, IE does not support FormData, so you should find another way
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<form id="data">
<fieldset>
<div>Asset File: <input id="image_file" name="image_file[]" type="file" /></div>
<div><input type="submit" value="Submit"></div>
</fieldset>
</form>
<script>
$(function() {
$("form#data").submit(function(event){
event.preventDefault();
var url = 'http://server.com/upload';
var image_file = $('#image_file').get(0).files[0];
var formData = new FormData();
formData.append("image_file", image_file);
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (status) {
// do something on success
}
});
return false;
});
});
</script>

Your web site files are stored at the server. JavaScript runs at the client-side.
The images must be stored somewhere. But the client-side JavaScript have access to the user's browser window (or tab). and user's cache. You cannot write files at the server storage using only client-side JavaScript.
The ways images are uploaded and downloaded:
Download:
You send request to the server using JavaScript (ajax for example). In this request you say: "GET http://my-site/images/cool-dog.png" This is static request that try to access images/cool-dog.png from your public folder on the server. Every server has option that allows you to determinate which folder will contain all the files for the static requests.
STATIC request is when you try to access a file with an extension (cool-dog.png)
Upload:
As we know, everybody can write client-side JavaScript to the console: Every major browser has debugging tools. And everybody can send any kind of request to your server from Postman for example.
It will be bad to accept all of there request. Somebody may want to upload 100GB file at max speed. That may affect the application and server performance or even hack the application.
You need server-side logic to determinate which file is good for your server and where this file must be stored, since the JavaScript know only about client-side storage (cookies, localStorage, sessionStorage, cache, etc...).
Upload process is:
You send request from the client-side JavaScript to the server-side. For example : POST http://my-site/uploadImage with the image data.
The server-side accepts that request. For example: Router.get('uploadImage', function() {...Server side code...}). Since http://my-site/uploadImage is dynamic path (we do not have extension) The server-side Router will wait for this kind request and if it's requested the server-side code must check the file size and extension (.png or .dll) and etc... And if the file is good for your application then you can write this file to the server location.
The different server languages and technologies has different methods for processing requests and writing files.
If you want to extend your knowledge you need to learn at least one server-side language and technology. You cannot make flexible applications only with client-side logic.
If you are familiar with JavaScript yet. You may want to learn NodeJS. This site contains great tutorials for NodeJS beginners.
PHP is also easy to learn if you can found some good tutorials.
Here is tutorial how to upload files using nodeJS
and here is another for PHP

Related

In JavaScript, are there any security issues associated with FileReader?

Consider the following piece of code:
(Partial) HTML:
<input type="file" accept=".txt" id="theFile" class="button" />
(Partial) JavaScript:
$('#theFile').on('change', function(e){
readFile(this.files[0], function(e) {
var text = e.target.result;
})
})
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
reader.readAsText(file);
}
My question is, is there any security risk involved in the use of FileReader, particularly in this case, when deployed with readAsText? For example, what happens if the file chosen is not a .txt but something else? Is it possible for a malicious user to attack the hosting website in some way?
If it's relevant for the purposes of the question, the full code simply retrieves a text from a .txt file and prints parts of it on screen.
Any other detail or information required, I'd be happy to provide.
Yes, you are fine here there is no security issues.
The code is been executed in the users browser not the server, so even if it was malicious, they would only be infecting themselves.
The code above is only reading the file as text, so even if it was malicious it won't be getting executed.
Were you do need to be careful when creating a website, is if you allow a user to upload malicious files, and then somehow allow them to execute them server side. An example would be were a PHP website didn't have correct security, you allowed them to upload a bad PHP file and this directory was available via the website, the PHP file could then be executed server side by them just putting www.mywebsite.com/upload/danger.php into there browser.

What is server-side scripting ajax

Hi I'm new to programming and making a project exactly like these Real time GPS Tracker on JUST HTML / JS and Google Maps to be run on a handphone
My Next step is all users should see others location and one of the answers said
you'd have to send the points to a server-side script using AJAX.
I know how ajax works i just don't know what he meant by server-side script
$.ajax({
url: "sample.php",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
My Questions is:
Is the code above consider a server-side script? if no any examples
Should i make new .php file?
You have a file that exist in you server so one cannot access it using their browesers.In your case that test.html file is residing in server. it can be .php file .js file ....
The code above is not a server side scripting language as the url is still point to a .html page.
A server side scripting language is a language that runs on the server rather than on the client. example of a server side scripting language is php.

Ajax put to add XML entries into XML file

I am trying to add some emails taken from an inputbox into a .txt file present on my webserver. Here is the code :
email = document.getElementById("mail").value;
$.ajax({
url: 'maillist.txt',
datatype: 'text',
type: 'PUT',
data: email + '; ',
success: function(data) {
alert('Should have work yay!');
}
});
but that doesn't work on any browser. :(
I have tried using javascript classic methods but it was a no go as well...
I would need either a PUT or POST method, either jQuery or JS, to be able to do this on internet explorer 8 and up as well as firefox and chrome. Emails should appear in the text file as
email1#cooldomain.com; email2#cooldomain.com; .....
Just so it works with our in-house VBA Macro. :)
Also, could there be a method for dropping data into XML files (aka create a new XML entry with form data)? And also, is it possible to upload a file from client side to server side using jQuery? Because i would need users to fill up forms and drop their data into an XML file, and link up a file they choose with that. That way they could add stuff into the XML themselves and they would show up brand new into the webpage.
Kindoff "reddit" or "4chan" like if you know the references.
Thanks for your time, really appreciated!
You can't post from a browser to a text file on the server side. You need to have some sort of code on the server side that will receive the HTTP PUT, and persist the data to a file local to the server.

Read all files in a local folder offline without using ActiveXObject or php

I'm a beginner! I need to read data inside txt files in a local folder offline. I know the folder path, but I don't know the name of every single file.
C:\mypath\first.txt
C:\mypath\second.txt
C:\mypath\third.txt
...
To read a sigle file now I use:
$.ajax({url:"C:\mypath\first.txt",
success:function(result){
//...code for storing the data in a variable...
}
});
How can i read multiple file at once without know their name? something like:
$.ajax({url:"C:\mypath\*.txt",
success:function(result){
//...code for storing the data in a variable...
}
});
Thank you for any help!
You can use a file picker control (ie, <input type="file" multiple />) in a supported browser and have the user select the set of files to iterate. User input is the only way to get the list of files - you can't just go mucking about in a user's file system over the internet. All you can learn about the user's system is what the user tells you (eg, through <input type="file" multiple />).
And even then, you won't be able to read the file with a simple Ajax request. Same origin policies apply to local files. It may work if you test it on your own machine, but as soon as it hits the web, it will fail.
The only way to look through a client file system without user interaction is by using a Scripting.FileSystemObject ActiveXControl on windows in a non-internet based HTML Application (.hta file). So, since you don't want to use ActiveXControls, user input is your only option.
Edit: If you are creating a FireFox add-on, you can access the file system. See the documentation at mozilla.org for details.

How to upload an image from a remote website, by using javascript?

Is there any way I can do that? For example, I have an
<input type="file" id="upload_file" />
Obviously I can't just
$('#upload_file').val('http://www.site.com/path/to/image.jpg').parent().submit();
You can't do it.
Javascript won't let you read from other domains (for security reasons).
File inputs don't accept URL inputs (or for that matter paths) AFAIK.
I can't see how you will get this to work. What server side language are you using? Would it not be better to just make a direct request for the remote file from the server?
IF that site supports what are you trying to do it should work.
Most of file uploads are very strict, as you can't just upload a file wherever you want even if you know the upload script.
If host supports sending a link to the picture and he knows what to do with it ... I don't see why your script should not work.
<form method="post" action="http://www.example.org/">
<input type="text" name="upload_file" id="upload_file" value="" />
<input type="submit" onclick="$('#upload_file').val('http://www.example.org/example.jpg');">
</form>
Te begin with, you cannot do file uploads without a server-side tool. Sending a file to the server is pointless if there isn't anything on the side other to receive it.
Said that, if you already have a server-side language available and a file that's publicly reachable at a URL, the server-side language is perfectly capable of fetching the file by its own means. There's no need to use the browser as intermediary. You just need to send the URL in a regular <input type="text"> element.
If the file is not publicly reachable, e.g., it belongs to an intranet or is password-protected, it's probably simpler to instruct the user to type the URL in the browser's "Open file" dialoque. In many cases, the browser will download the file and fill the <input type="file"> control with the temporary downloaded file.

Categories