I am using Jasny Bootstrap to display file preview when it is selected.
<div class="fileinput fileinput-new" data-provides="fileinput">
<div>
<span class="btn btn-primary btn-file"><span class="fileinput-new"><span class="fa fa-camera"></span> Image 3</span>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div>
<input type="file" name="file" class="ephoto-upload" accept="image/jpeg"></span>
</div>
</div>
I would like to start submission of this image via ajax as soon as image is selected. I am using following code.
<script>
$('.ephoto-upload').change(function(){
if($(this).val()!='') {
var formData = new FormData();
formData.append('file', $(this)[0].files[0]);
$.ajax({
url: '/path/to/upload',
type: 'POST',
data: formData,
async: false,
success: function (r) {
if(r.success) {
//success work
}
},
cache: false,
contentType: false,
processData: false
});
}
});
</script>
Upload works fine but the preview of image is displayed after ajax upload is completed.So for sometime page get freezes and after that preview is displayed. But I want to display the preview as soon as image gets selected and after displaying the selected image, Ajax get execute.
You're setting your ajax async=false
that means the navigator is gonna freez until the image has been uploaded.
In other hand this is what you wanted:
<form>
<div class="fileinput fileinput-new" data-provides="fileinput">
<div>
<span class="btn btn-primary btn-file"><span class="fileinput-new"><span class="fa fa-camera"></span> Image 3</span>
<div id="preview" name="preview" class="fileinput-preview fileinput-exists thumbnail" style="width: 200px; height: 150px; display:block;"></div>
<img id="prevImg" name="prevImg" />
<input type="file" name="file" id="file" class="ephoto-upload" accept="image/jpeg"></span>
</div>
</div>
</form>
js:
$('.ephoto-upload').change(function(){
previewURL(this);
if($(this).val()!='') {
var formData = new FormData();
formData.append('file', $(this)[0].files[0]);
$.ajax({
url: '/path/to/upload',
type: 'POST',
data: formData,
success: function (r) {
if(r.success) {
//success work
}
},
cache: false,
contentType: false,
processData: false
});
}
});
function previewURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
//$('#prevImg').attr('src', e.target.result);
$('#preview').css("background", "url(" + e.target.result +")" + " right top no-repeat");
}
reader.readAsDataURL(input.files[0]);
}
}
I deleted the async=false
because default is true
.
Here's the demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With