In my web app,I need to upload a single file when a user selects that file and stay on the same html page.I am looking for a non-flash solution which probably uses jquery.and something which works on firefox.
By googling,I came across many plugins,most of them using elaborate html pages for showing input widgets / upload status indicators etc.I need something which I can use like this,using ajax.
mypage.html
<input type="file" id="myfileselect" > </input>
myjs.js
$(document).ready(function(){
$('#myfileselect').change(function(e){
//upload the file somehow
}
});
Is this possible?Can someone illustrate how I can do this?
I use this plugin in all my projects. Once the user selects the file, you simply call
$('#yourForm).ajaxSubmit()
and it will asynchronously upload your file.
http://jquery.malsup.com/form/
In your case, you would do it like this:
HTML
<form id="myForm">
<input type="file" id="myfileselect" > </input>
</form>
JQuery
$(document).ready(function(){
//set the options here
var options = {
url : 'yourScript.php',
method : 'post'
};
$('#myfileselect').change(function(e){
$('#myForm').ajaxSubmit(options);
}
});
Related
I am creating a responsive mobile website, and I want to be able to take and then upload a picture from the device. I have got this part working using
<form method="post" action="takephoto.php" enctype="multipart/form-data">
<input type="file" id="myfile" name="myfile" accept="image/*;capture=camera"/>
</form>
Now, what I am having trouble with is, after I have selected the picture that I want to use I do not know how to reference it later in my code. The reason I need to is I am using a .js library which allows me to upload a picture of a ISBN barcode and the .js file will read this file and spit out the ISBN as text which I will do more with later. (maybe link this to a Google Books API)
This is where I am getting the barcode scanner .js from: http://badassjs.com/post/654334959/barcode-scanning-in-javascript
I am relatively new to all of this, thanks for your help.
You will have to use ajax. This link contains some useful information for you.
Use ajax to get the picture uploaded and in the response, return the url or "failed". Then you can use in your js code,
if(response=="failed"){
//Handle upload failed
}
else {
//Handle url. Here response is your url actually.
// So to append the image to a given id, you would use,
$("#append_to_id").append("<img src='"+response+"'>");
}
Since the JavaScript library you are using is parsing an image on the page,
you have to show the image on the page after you have uploaded it.
So basically you need 4 steps to achieve this:
show an upload form (This is what you have done in the question);
grab the image uploaded in step 1 and save it to an accessible place
display the image on the screen
call get_barcode_from_image.js to parse it
Here's a piece of code for reference. It contains all the 4 steps above.
<?php
// step 2: save the image
if ($_FILES['myfile']['error'] == 0) {
move_uploaded_file($_FILES['myfile']['tmp_name'], 'u/barcode.jpg');
?>
<!-- step 3: show the image -->
<img src="u/barcode.jpg" id="barcode">
<script src="get_barcode_from_image.js"></script>
<div id="result"></div>
<!-- step 4: parse the barcode -->
<button onclick='document.getElementById("result").innerHTML = getBarcodeFromImage("barcode")'>scan</button>
<?php
}
?>
<!-- step 1: show the upload form -->
<form method="post" action="barcode.php" enctype="multipart/form-data">
<input type="hidden" name='a' value='b'/>
<input type="file" id="myfile" name="myfile" accept="image/*;capture=camera"/>
<input type="submit" value="submit" />
</form>
Of course you can use ajax or so to get better user experience, but the process won't change.
I have a page file-upload.jsp with the code snippet below:
<form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upload_file" multiple="" />
<input type="submit" value="Update" />
</form>
I have 2 questions:
The moment I select some files, i.e the onchange event of the input type file, the file(s) should get uploaded.
I have a Java page that receives multipart request parameter and uploads the file to the said location. My problem is the form submission onchange, so that the Java file can proceed with further operations.
I googled and went through lot of articles. Some say it's not possible to upload files directly via Ajax, some say submit the form to an iframe via Ajax/jQuery.
I tried a lot of code from internet, such as this:
$(document).ready(function(){
$('upload_file').change(function(){
var data = new FormData();
data.append('file', $(this[0].files[0]));
$.ajax({
url: 'photo.jsp',
type: 'post',
contentType: attr('enctype', "multipart/form-data"),
data: data,
success: function(data){
alert(data);
}
})
});
});
but could not get the expected results.
I also need a progress bar for the upload operation.
Look at this example using an IFrame, is in PHP but changing the action should do the trick
Ajax Style File Uploading Using Hidden IFrame
Since you're already using jQuery, I would definitely go for the jQuery Form Plugin, which allows you to do form uploads via AJAX, even if the form contains a file input.
There is an example on its website available that shows how to display a progress bar.
Look at this example it is exact as you want
http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/asyncfileupload/asyncfileupload.aspx
I'm new at AJAX and am working on an implementation of a form that will upload a name and a file to a php file that processes the data and sends it to a database for insertion using mysqli. I've tested the php file and it does work. My problem is in the AJAX code. I've tried an implementation using XMLHTTP and using jQuery. Both leave the page and open the PHP file in the browser. As a disclamer, I posted this question to another coding site, a fight ensued between two posters, and so I'm trying here to hopefully get a reasoned and calm response with productive suggestions.
I realize that currently "get" is being sent to the PHP file rather than "post", but PHPStorm tells me that "post" is not available in that form. What's my alternative? Am I on the right track or is there another direction I should go? How do I refresh only the form and keep the PHP page from loading?
Here's the relevant snippet of my code,
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.validate.js"></script>
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var url = $(form).prop('action');
var dataToSend = $(form).serialize();
var callback = function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived)
};
var typeOfDataToReceive = 'html';
$.get(url, dataToSend, callback, typeOfDataToReceive),
return false;
}
});
});
</script>
</head>
<body>
<form id="addForm" action="addInfo.php" enctype="multipart/form-data">
<input type="hidden" name="usingAJAX" value="false"/>
<label for="aname">Name: </label>
<input type="text" name="aname" id="aname" class=required/>
<label for="aimage">Photo: </label>
<input id="aimage" type="file" name="aimage" class="required">
<input type="submit" value="ADD"/>
</form>
</body>
</html>
Until recently you could not upload files with ajax.
You still cannot upload the file directly with ajax, but you can do it programatically with HTML5 File API.
Still, if you are looking for simple solutions, try traditional IFrame approach.
If you want bleading edge technology, use File API. Here is some tutorial how to read files with javascript.
The steps to upload with ajax:
Read file with javascript FileReader API.
Post the content of the file, encoded to base64 or something, to the server.
Serverside, decode the contents of the file programatically.
When using this approach, the file will not be handled as a file upload by the server. It will be just another request field with text inside. It is up to you to decode it on the server side.
The filereader API allows you to read the file portion by portion and upload fragments of file, so it would be possible to upload huge files in chunks, but you need to handle it yourself.
Try using plugin jQuery form.js http://www.malsup.com/jquery/form/#file-upload You can upload files with ajax and jQuery. It is easy to use, just need to give #form-id in ajaxSubmit function.
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var options = {
url : $(form).prop('action'),
dataToSend : $(form).serialize(),
callback : function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived) },
typeOfDataToReceive = 'html';
//your options here
};
$('#yourFormid').ajaxSubmit(options);
return false;
}
});
});
</script>
This jquery plugin allows you to turn any element into a file input element. http://plugins.jquery.com/project/custom-file
But to actually upload the file, the only documentation i could found is this:
To upload the chosen file to a server you should then attach the input element to a form element
how can i do that?
I think you need to create an html form and append the input to the form, and if you need to submit, you can do it via a submit button or via $.submit
# from http://www.daimi.au.dk/~u061768/file-input.html
<script type="text/javascript">
$(function() {
$('button').button().add('#foo, a').file().choose(function(e, input) {
$(input).appendTo('#TheForm').
attr('name', 'a-name').
attr('id', 'an-id');
});
});
</script>
...
<form method="post" enctype="multipart/form-data" id="TheForm" action="/path/in/your/server/">
<input type="submit" value="send">
</form>
Anyway this is not the best plugin for submiting the files via ajax.
The uploading itself is not of the scope of this plugin. You should see this with your server side technology.
I have a form which I'm using to upload files. In current situation if a user choose an image from his computer he have to click button upload to upload the image. I'm trying to find a way to skip the step with a button pressing.
How to call a javascript function when the file is selected from user ?
The onchange event is fired when a user specify a file for the upload filed. You could go about something like this:
<input type="file" name="someName" id="uploadID" />
Javascript:
var el = document.getElementById('#uploadID');
el.onchange = function(){
// your code...
};
However, javascript validation is good idea but make sure that you do the actual validation on the server-side :)
Using the example above...
<input type="file" name="someName" id="uploadID" />
JavaScript
document.getElementById('uploadID').addEventListener('change', () => {
//Your code...
});