I have an input tag like
<form id="myForm">
<!-- has lots of inputs above like username password etc -->
<input type="file" id="user_photo" name="user_photo" tabindex="6" size="6" class="" accept="jpeg|png|jpg|gif|PNG|JPEG|GIF|JPG" >
OnChange, I would want to upload an image through AJAX and save it in server. After saving, it should display in a preview div where I can use jCrop to crop as user wishes and save it again to the server (after cropping) when user clicks submit button.
If you have a better method please tell me.
inshort, I just want to trigger an ajax post request with the file contents and save it into my uploads folder without sending the rest of the form elements.
I use codeigniter. I have tried fileuploader by valum.. didnt give me the result.
Answer was stolen from here: Can i preview the image file who uploaded by user in the browser?
Use the HTML5 File Api to load the image client side.
Then use jCrop at the after loading the image into a tag.
Then (I'm assuming) use jCrops onRelease method to do the Ajax call.
That way its only one ajax call, and its already modified
<img id="preview" src="placeholder.png" height="100px" width="100px" />
<input type="file" name="image" onchange="previewImage(this)" accept="image/*"/>
<script type="text/javascript">
function previewImage(input) {
var preview = document.getElementById('preview');
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
preview.setAttribute('src', e.target.result);
$('#preview').Jcrop({
onRelease: yourAjaxFunctionToSubmitToServer
});
}
reader.readAsDataURL(input.files[0]);
} else {
preview.setAttribute('src', 'placeholder.png');
}
}
</script>
Obviously this will need to be modified a bit to suit your needs, but you get the idea.
Related
I have a single image form I would like to upload my images with for a store page. It simply needs to be clicked, show the upload box, and then autoSubmit when they select the image and replace the one image with the new uploaded item.
Here is the current page layout, with no actual upload button. On image click, we will show the upload windows on users PC:
This is the code for the highlighted area in the HTML field
<div class="uploader">
<form method="POST" id="upload_image">
<img src="/img/upload.png" id="imageUpload" alt="upload" />
</form>
</div>
So once the form submits, using an Ajax request, when it returns and is successful I plan to store the image name (usually the current time() as filename) as a session variable, now I need to show a Loading... image while the upload process happens and then replace the imageUpload with the new image located in /img/thumbs/NEWIMAGENAMEHERE.png.
Question Time
Is there a jQuery function that I can use to replace the image with the loading image and then the loaded image once upload completes? Is there a jquery library already for SINGLE image upload like this? all the library's I have found work for multiple images and since we only support one image on this store layout, we don't want multiple image upload.
Thanks
Thanks to suggestion from #aron9forever I have decided instead of upload the image right away on it's own, I would simply display the image and then upload on form submit. This does pose the annoying issue that when they submit the form, if there is an issue, that they need to re-click upload image but I may have a way around that using $_POST variables.
<div class="uploader">
<img id="imagetoUpload" src="/com/img/upload.png" alt="upload">
</div>
<input type="file" id="productImage" style="display:none;" name="img" value="">
Using this jQuery
$(function() {
function readURL(input) {
if(input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imagetoUpload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
};
$("#productImage").change(function(){
readURL(this);
});
$("#imagetoUpload").click(function() {
$("input[id='productImage']").click();
});
});
On one of my current projects, I am allowing users to upload images and set them as profile pictures.
The image initially will be stored in a temporary folder until the user crops & saves, or cancels the upload. Of course, there will be cases where they won't actually hit the cancel button. So I have to go through the temp folder and remove images not used after x minutes.
I can think of one way to do this, which would store the image data in MySQL, but I would rather just keep everything on Apache - though I'm not sure what language I'd use to actually perform the search and delete function.
Would this be a cron job?
If the crop and save function is all JS I would recommend you to use the users local file and upload on "save".
JavaScript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
// jQuery
$("#imgInp").change(function(){
readURL(this);
});
// plain JS
document.getElementById('imgInp').onchange = function(){
readURL(this);
}
HTML:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
jsfiddle
Credit to Preview an image before it is uploaded
I have an input field in which I am inserting value through browse button now i want to copy that value from input field to an src tag so that i can preview the image which user has just uploaded
here is my code
<input class="text-input" type="text" name="logo" id="logo" onclick="tinyBrowserPopUp('image','logo','client_logos');"/>
I want to copy selected value from above input field to
<img src="myimage" />
You just can't directly show it from the user's computer instead you will need to first upload it to your server and then show it. Uploading the file using ajax would create the same effect you want. Also take a look at: FileReader API # MDN
Update: As you have the image already on the server try the code below
Try this code:
HTML:
<input class="text-input" type="text" name="logo" id="logo" onclick="tinyBrowserPopUp('image','logo','client_logos');" />
<img src="myimage" />
JS:
setInterval(react, 5000);
function react() {
document.getElementByTagName("img").src = document.getElementByName("logo").value;
}
Add an id to the img tag and use
var imagepath = $('#logo').val();
$('#myimg').attr('src', imagepath);
inside the function you fire when the input is changed
I got this working with the code below. I like to put the functions on body so that even if the class is added afterwards via AJAX the "change" command will still trigger the event.
My approach does use jQuery.
HTML:
<input class="text-input" class="classhere" type="text" name="logo" id="logo" />
<div class="imagearea"></div>
JS:
$("body").on("change",".classhere",function(){
//Equivalent of getElementById
var fileInput = $(this)[0];//returns a HTML DOM object by putting the [0] since it's really an associative array.
var file = fileInput.files[0]; //there is only '1' file since they are not multiple type.
var reader = new FileReader();
reader.onload = function(e) {
// Create a new image.
var img = new Image();
img.src = reader.result;
$(".imagearea").html(img);
}
reader.readAsDataURL(file);//attempts to read the file in question.
});
This approach uses the HTML5 File System API's to read the image and put it into a new javascript img object. The key here is readAsDataURL. If you use chrome inspector you will notice the images are stored in base64 encoding.
The reader is Asynchronous, this is why it uses the callback function onload. So make sure any important code that requires the image is inside the onLoad or else you may get unexpected results.
I'm trying to use Jasny's Bootstrap. This is nice work!
I coudn't find solution for bootstrap upload image on page http://jasny.github.com/bootstrap/javascript.html#fileupload
With bootstrap-fileupload.js, how can I upload image using Ajax?
I asked this question to directly ARNOLD DANIELS who is owner of Jasny's Bootstrap.
Here is his answer:
The whole point of the image preview is that the picture is show right
away, without the need to upload it to the server using AJAX. So it
stays just a regular form. You can post a form using AJAX
http://api.jquery.com/jQuery.post/ if needed.
If you do want to upload the image using AJAX and don't want to use a
form, checkout
http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
I used this sample with removing database releated lines and worked perfectly for me !
First you need to register the css and js files:
If you are using Yii Framework:
$cs = Yii::app()->clientScript;
$cs->registerCSSFile("/css/fileupload.css");
$cs->registerScriptFile('/js/fileupload.js', CClientScript::POS_END);
Or
<link rel="stylesheet" type="text/css" href="/css/fileupload.css">
<script type="text/javascript" src="/js/fileupload.js"></script>
Then register the following script:
$cs->registerScript("imageUpload", "$('.fileupload').fileupload({uploadtype: 'image'});", CClientScript::POS_END) ;
Or
<script type="text/javascript">
$('.fileupload').fileupload({uploadtype: 'image'});
</script>
Then add the following HTML code to your page:
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-preview thumbnail" style="width: 200px; height: 150px;"></div>
<div>
<span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" /></span>
Remove
</div>
</div>
I came across this question on Google and just wanted to show I did it for anyone else interested (even if it's not the most elegant way)
$(document).ready(function(){
$('.fileinput-preview').bind('DOMNodeInserted', function(event) {
var imgdata = ($('.fileinput-preview img').attr('src'));
$.post( "upload.php", { imgdata: imgdata})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
})
})
This above piece of code detects when the file input preview has changed. It then finds the base64 data from the image tag, and uses jquery to post it to upload.php.
Upload.php simply takes the base64 image data and saves it as an image
$imgdata = $_POST['imgdata'];
$ifp = fopen("newimage.jpg", "wb");
$data = explode(',', $imgdata);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
The upload on jasny is more than a preview or client side upload management instead an ajax, probably you need tp use other method or plugin, cause the jasny upload will send the preview path using the binary image displaying
To make a nicer experience of a file upload, I am faking an ajax request i.e The user clicks submit, the form dissapears a loading graphic appears and after a view seconds the page refreshs to show their newley upload image.
However since adding the jquery in my file upload always returns the same errors,
You did not select a file to upload. Why is this? This is my form,
<div id="picture_upload">
<div class="loading"></div>
<?php echo form_open_multipart('my_profile/do_upload'); ?>
<strong>Choose pictures to upload</strong>
<p>Max file size: 1MB .jpeg, .gif, .png or .bmp</p>
<input type="file" name="userfile" />
</div>
<!--<div id="webcam_upload">
<p>Hello</p>
</div>-->
</div>
<div id="bottom"><table><tr><td><input type="submit" id="submit_upload" value="Upload a picture" class="button green rounded_5 small" /></td><td>or</td><td><a href="#" id="close_modal" />Cancel</a></td></tr></table></div>
and my js,
$("#submit_upload").click(function(e){
//alert("here");
setTimeout(function() { $("#picture_upload form").submit();}, 6000);
$("#picture_upload").children().hide();
$(".loading").show();
setTimeout( function() { location=$("#picture_upload form").attr('action') }, 1500 );
return false;
});
The upload function is just your basic upload function from codeigniter.
For security reasons You can't upload a file using an XmlHttpRequest object (AJAX).
Alternative solutions are:
Load your file submission form in an iframe and post that with JS
Use a flash file uploader
Use HTML5
Here's a jQuery plugin that appears quite popular: http://www.uploadify.com/
Try like this,
$("#submit_upload").click(function(e){
//alert("here");
setTimeout(function() { $("#picture_upload form").submit();}, 6000);
$("#picture_upload").children().hide();
$(".loading").show();
return false;
});
And then redirect/reload the page using php
header('Location: URL_TO_REDIRECT'); //put it in your end of upload script in php file
If you don't want to redirect from PHP then, you can use
jQuery Form plugin http://jquery.malsup.com/form/#file-upload
SWFUpload http://demo.swfupload.org/v220/index.htm
(there are many libraries for uploading file.)
If you want to learn how to build your own upload using jQuery here is a good article - http://www.peachpit.com/articles/article.aspx?p=1766159