WHAT I'M DOING
I'm trying to implement profile picture changing in php/jquery. When an image is uploaded the preview of the image is shown.
WHAT I REQUIRE
I want to get the src of the previewed image. When i use $('img').attr('src'); it gives the src of the old image and not the new previewed image.
SCRIPT
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var image = $('#img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
HTML
<div class="pic">
<form id="form1" enctype="multipart/form-data">
<img src="profile.jpg" width="150" alt="profile" title="" id="img"/>
<span>Change Picture?</span>
<div class="up">
<input type='file' name ="file" id="imgInp" />
</div>
<input type="submit" name="picture" id="picture" value="Update"/>
</form>
</div>
There is a new security "feature" in IE 8 that hides the real path of the selected file from JavaScript calls (it returns c:\fakepath). This seems to only be activated for "Internet" servers ... not Local intranet servers...
See here for more information about C:\fakepath
Edit
Also, you should consider removing this line of code (you don't need it in your script)...
reader.readAsDataURL(input.files[0]);
Related
My JQuery populates $_FILES only when click on input type file but not when drop in a file.
All the examples, tutorials, documentation I have found is about using Ajax or pure JavaScript. None is what I want to do. I have found also plently of plugins, libraries, ... I just want to be able to drop a file.....
The FORM:
<form id="item-form" role="form" method="post" enctype="multipart/form-data">
<div id="image-holder" class="dropBox">
<img src="" style="width: 100%; padding: 10px;display: none;">
</div>
<div id="fileBox">
<input type="file" name="image_file_input" id="image_file_input" />
</div>
<button type="submit" name="submit">SAVE</button>
</form>
The JQUERY:
$(".dropBox").on("drop", function(e) {
e.preventDefault();
e.stopPropagation();
runUpload( e.originalEvent.dataTransfer.files[0] );
});
$(".dropBox").click(function(){
$("#image_file_input").click();
});
$('input[type=file]').on('change', function(){
runUpload( this.files[0] );
});
function runUpload( file ) {
var reader = new FileReader(), image = new Image();
reader.readAsDataURL( file );
reader.onload = function( file ) {
var image_holder = $("#image-holder");
image_holder.empty();
$("<img />", {
"src": file.target.result,
"class": ""
}).appendTo(image_holder);
$("#dropBox").hide();
$(image_holder).show();
}
The PHP:
if ( !empty($_FILES) ) {
echo '---> Files not empty ';
}else{
echo '---> Files empty ';
}
I don't want to use Ajax. I'm only showing the relevant part of the code to concentrate in the issue.
If I click on the dropBox or I drop a file (image) into the dropBox element I can see the image selected in the image_holder div.
When the form is submited if the file is from a click event it works perfectly but when is from a drop event $_FILES is empty.
I'm convinced the problem is what I pass to the runUpload function when dropping. I have tried all sort of things but unable to see what is wrong.
I want the full path of a selected image to be displayed once Choose File button is clicked. Any idea on how to do that?
In your $_POST handling, use the following:
$fullpath = $_FILES["Name_Of_The_Input_Field_For_The_File"]["tmp_name"];
See Getting complete PATH of uploaded file - PHP for a similar issue.
Instead of doing a double POST, you can do something like this:
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]);
}
}
$("#imgInp").change(function() {
readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Remember, that just because you've selected a file to upload doesn't mean its been uploaded. The server still hasn't received the data, thus, doing this on the client side makes a little more sense from what i gather you want to do.
(stolen from: Preview an image before it is uploaded)
I have a modal containing a form and an iframe.
The form has a file field and post to the iframe.
The php controller return the uniqid (basically the name) of the uploaded file.
The upload works well and my iframe contains the uniqid.
I would like to display this uniqid on my main page.
My issue is that I don't know how to wait the end of the upload to show the uniqid.
The form and iframe :
<form id="uploadForm" enctype="multipart/form-data" action="{{ path('lesson_upload') }}" target="uploadFrame" method="post">
<label for="uploadFile">Document :</label>
<input id="uploadFile" name="uploadFile" type="file" />
<br /><br />
<input class="btn btn-primary" id="uploadSubmit" type="submit" value="Upload" />
</form>
<div id="uploadInfos">
<div id="uploadStatus">Aucun upload en cours</div>
<iframe hidden id="uploadFrame" name="uploadFrame"></iframe>
</div>
The JavaScript to fill the modal with the form :
$(document).on('click', '#computer-upload', function ()
{
var url = Routing.generate('lesson_upload_computer');
$.get(url, function (data)
{
$('#modal-various .modal-body').html(data);
return false;
});
return false;
});
The iframe at the end of an upload :
<div id="uploadInfos">
<div id="uploadStatus">Aucun upload en cours</div>
<iframe hidden="" id="uploadFrame" name="uploadFrame">
#document
<html>
<body>
<body>533ebac647b7e</body>
</body>
</html>
</iframe>
</div>
Does anyone have an idea ?
Thanks !
If you don't use an AJAX upload, after a little research, you cannot add an event that detects when the upload has finished.
You now have 2 options:
Fetch the id from the iframe every ~100ms and if it is not empty or null, the id will be in:
document.checkForId = function() {
id = $('#uploadFrame').contents().find('#idInIframeDivOrOtherContainer');
if (id) {
window.clearInterval(intervalId);
}
};
$(document).ready(function() {
intervalId = window.setInterval('document.checkForId', 100);
});
When posting data, return javascript that sets the id in the main page (if you have jquery in the iframe):
<script>
$(document).ready(function() {
$('#divInParentWindow', parent.document).text('<?php echo $id; ?>');
});
</script>
If your iFrame has its source on the same server/domain level as your main page. You could simply define a function at your main page
function iframeHasLoaded() {
var body = document.getElementById('uploadFrame').contentWindow.document.body.innerHTML;
}
And, from your iFrame
window.onload=function() { parent.iframeHasLoaded() };
This should work.
I am new here apologies for any anomalies, The task I've been given is to create an image/audio file upload or link page with preview before POST.
Not sure how late I am but just discovered Html5 audio tag, I'd like to know how to preview an audio file on selection before upload.
here's my upload form:
<form id="attach" action="imageUpload.php" method="POST" enctype="multipart/form-data" >
<h2>Select An Audio File to Upload</h2>
<br>
<div>
<input type='file' id="files" name="files" multiple onchange="previewAudio(this);" />
<br>
<br>
<output id="list"></output>
<ul>
<li>
<label for="caption">Caption</label>
<input type="text" maxlength="30" name="caption" id="caption" />
</li>
<li>
<textarea id="desc" name="desc" rows="4" cols="32">Description
</textarea>
</li>
</ul>
<audio controls>
<source id="test3" src="" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<input type="submit" value="Upload"/>
</div>
</form>
here is the code I've been playing with tryin to get it to preview:
function previewAudio(input)
{
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#test3').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
I'm most adamant that this should work but its not, any fixes or new methods will be highly appreciated
Thanks in advance.
Thanks JWarner that link was a nice starting point, learnt a lot in my almost 5 hours researching this and ended up finding a solution here Reading files in JavaScript using the File APIs
here is how I did it:
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('files').addEventListener('change', handleFileSelect,false);
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (f.type.match('image.*')) {
var reader = new FileReader();
alert('e.target.result');
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '" width="230" height="270"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
}else if (f.type.match('audio.*')){
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<audio controls><source src="', e.target.result,' "type="audio/ogg"><source src="', e.target.result,' "type="audio/mpeg"></audio>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
}
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
} }, false);
Please point out any weak points in this code if there are any
Thank You
Here is something that may help you, allowing you to circumvent the use of Java and make use of bare HTML instead.
I also hope it doesn't insult you to point out that, I'm not sure there's a way to just "preview" a song, and that you may have to host shortened versions of the song that serve as preview-length, for your scripts to play, rather than having the code automatically truncate them.
(beginner)
I'm having trouble uploading my file. I see the filename being posted to the database, but the file is not being posted to the images folder. It seems as though nothing is happening. Here is my following code, please advise me what I need to change:
<?php
//the $art variable gets posted to a database eventually
$art = mysql_real_escape_string(stripslashes($_FILES["art"]["name"]));
$art_ext = pathinfo($art, PATHINFO_EXTENSION);
$art = md5($art).".".$art_ext;
if($art!=""){
move_uploaded_file($art, "images/".$art );
}
?>
<script type="text/javascript">
$(function(){
image_upload = {
UpdatePreview: function(obj){
// if IE < 10 doesn't support FileReader
if(!window.FileReader){
// don't know how to proceed to assign src to image tag
} else {
var reader = new FileReader();
var target = null;
reader.onload = function(e) {
target = e.target || e.srcElement;
$("#imageupload").attr("src", target.result);
};
reader.readAsDataURL(obj.files[0]);
}
}
};
});
</script>
<form action="new.php" method="post" enctype="multipart/form-data">
<input type='file' name='art' id="file" onchange='image_upload.UpdatePreview(this)' value="Upload" accept="image/gif,image/jpeg,image/png"/>
</p>
<p>upload a image! (.gif, .jpg, .png formats allowed. 5MB max)</p>
<img id="imageupload" src="1x1.png" alt="test" />
<input type="submit" class="smallbtn4" style="cursor:pointer;" value="post"/>
</form>
Here's the format for move_uploaded_file():
$path = 'images/';
move_uploaded_file($_FILES['art']['tmp_name'], $path.basename($_FILES['art']['name']));
when using move_uploaded_files() your destination path should also include the name of the file....right now your destination path is:
images/
it should be:
images/nameOfImg.ext
Hope this helps!
EDIT:
After seeing the comment by #enhzflep, you should also hash the name of the file and create your filename string before using it in move_uploaded_file();