Haber, os cuento:
Tengo un problema a la hora de trabajar con el envios de imagenes y datos mediante ajax. Quiero conseguir en un formulario enviar una imagen sin que se recarge la pagina (Esto lo consigo), y una vez subida la imagen rellenar los datos del formulario. Uno de esos datos es el nombre de la imagen. Tengo que pasar el nombre de la imagen a un input del formulario pero no soy capaz. Os pongo el codigo:
jmusic.html.php (Formulario):
<script type="text/javascript" src="http://localhost/components/com_jmusic/inc/ajaxupload.js"></script>
//Este esl formulario par asubir la imagen
<fieldset ><legend>Ajax Image Upload</legend>
<form onSubmit="return disableForm(this);" action="wizecho_upload.php" method="post" name="f" id="wizecho" enctype="multipart/form-data">
<input type="file" name="file" id="archivo" />
<button onClick="return disableForm(this),ajaxUpload(this.form,'<?php echo $mosConfig_live_site;?>/components/com_jmusic/wizecho_upload.php', '<br>Uploading image please wait.....<br>');return false;">Upload Image</button>
</form>
<div id="UPLOAD"></div>
</fieldset>
....
....
//Formulario de datos
<form action="index2.php" method="post" name="adminForm" id="adminForm">
.....
.....
//En este imput quiero añadir el nombre de la imagen una vez procesada
<input class="inputbox" type="text" name="imgfilename" id="imgfilename" size="40" readonly="true" value="" />
.....
ajaxupload.js (Este scipt es el que hace posible subir la imagen sin recargar la pagina):
<!--
alert("Ha cargado el script");
var myDomain = "";
if ( document.domain!="localhost" ) {
myDomain = /(http?:\/\/[^\/]+)/.exec(window.location.href)[1] + '/';
} else {
myDomain = "http://localhost/";
}
function disableForm(theform) {
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var tempobj = theform.elements[i];
if (tempobj.type.toLowerCase() == "submit")
tempobj.disabled = true;
}
return true;
}
}
// -->
function $m(theVar){
return document.getElementById(theVar)
}
function remove(theVar){
var theParent = theVar.parentNode;
theParent.removeChild(theVar);
}
function addEvent(obj, evType, fn){
if(obj.addEventListener)
obj.addEventListener(evType, fn, true)
if(obj.attachEvent)
obj.attachEvent("on"+evType, fn)
}
function removeEvent(obj, type, fn){
if(obj.detachEvent){
obj.detachEvent('on'+type, fn);
}else{
obj.removeEventListener(type, fn, false);
}
}
function isWebKit(){
return RegExp(" AppleWebKit/").test(navigator.userAgent);
}
function ajaxUpload(form,url_action,msg){
var id_element='UPLOAD';
var html_show_loading = msg + "<img src=\'" + myDomain + "components/com_jmusic/img/img_load.gif\' border=\'0\' />";
var html_error_http ='<img src=\'img/error.gif\' width=\'16\' height=\'16\' border=\'0\' /> Error in Upload, check settings and path info in source code.';
var detectWebKit = isWebKit();
form = typeof(form)=="string"?$m(form):form;
var erro="";
if(form==null || typeof(form)=="undefined"){
erro += "The form of 1st parameter does not exists.\n";
}else if(form.nodeName.toLowerCase()!="form"){
erro += "The form of 1st parameter its not a form.\n";
}
if($m(id_element)==null){
erro += "The element of 3rd parameter does not exists.\n";
}
if(erro.length>0){
alert("Error in call ajaxUpload:\n" + erro);
return;
}
var iframe = document.createElement("iframe");
iframe.setAttribute("id","ajax-temp");
iframe.setAttribute("name","ajax-temp");
iframe.setAttribute("width","0");
iframe.setAttribute("height","0");
iframe.setAttribute("border","0");
iframe.setAttribute("style","width: 0; height: 0; border: none;");
form.parentNode.appendChild(iframe);
window.frames['ajax-temp'].name="ajax-temp";
var doUpload = function(){
removeEvent($m('ajax-temp'),"load", doUpload);
var cross = "javascript: ";
cross += "window.parent.$m('"+id_element+"').innerHTML = document.body.innerHTML; void(0);";
$m(id_element).innerHTML = html_error_http;
$m('ajax-temp').src = cross;
if(detectWebKit){
remove($m('ajax-temp'));
}else{
setTimeout(function(){ remove($m('ajax-temp'))}, 250);
}
}
addEvent($m('ajax-temp'),"load", doUpload);
form.setAttribute("target","ajax-temp");
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
if(html_show_loading.length > 0){
$m(id_element).innerHTML = html_show_loading;
}
form.submit();
}
wizecho_upload.php (Este ultimo, gestiona la imagen, la sube, cambia el nombre, ect):
<?php
//** Wizecho ajax image/file uploader**//
function resize_image($src_file, $dest_file, $new_size, $method, $dest_qual){
$imagetype = array( 1 => 'GIF', 2 => 'JPG', 3 => 'PNG', 4 => 'SWF', 5 => 'PSD', 6 => 'BMP', 7 => 'TIFF', 8 => 'TIFF', 9 => 'JPC', 10 => 'JP2', 11 => 'JPX', 12 => 'JB2', 13 => 'SWC', 14 => 'IFF');
$imginfo = getimagesize($src_file);
if ($imginfo == null) die("ERRORE: Source file not found!");
$imginfo[2] = $imagetype[$imginfo[2]];
// GD can only handle JPG & PNG images
if ($imginfo[2] != 'JPG' && $imginfo[2] != 'PNG' && ($method == 'gd1' || $method == 'gd2'))
mosRedirect( "index.php?option=com_jmusic&task=upload", "ERROR: GD solo trabaja con archivos JPG y PNG." );
// height/width
$srcWidth = $imginfo[0];
$srcHeight = $imginfo[1];
echo "Creating thumbnail from $imginfo[2], $imginfo[0] x $imginfo[1]...<br>";
$ratio = max($srcWidth, $srcHeight) / $new_size;
$ratio = max($ratio, 1.0);
$destWidth = (int)($srcWidth / $ratio);
$destHeight = (int)($srcHeight / $ratio);
if (!function_exists('imagecreatefromjpeg')) {
die('GD image library not installed!');
}
if (!function_exists('imagecreatetruecolor')) {
die('GD2 image library does not support truecolor thumbnailing!');
}
if ($imginfo[2] == 'JPG')
$src_img = imagecreatefromjpeg($src_file);
else
$src_img = imagecreatefrompng($src_file);
if (!$src_img){
$ERROR = $lang_errors['invalid_image'];
return false;
}
$dst_img = imagecreatetruecolor($destWidth, $destHeight);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $destWidth, (int)$destHeight, $srcWidth, $srcHeight);
imagejpeg($dst_img, $dest_file, $dest_qual);
imagedestroy($src_img);
imagedestroy($dst_img);
}
//******** START SETTINGS ****************//
$root = $_SERVER["DOCUMENT_ROOT"]; // W:/www
$host = "http://".$_SERVER['HTTP_HOST']; // http://localhost
$up_size = 10000; //upload size in KB
$icons = "{$base}/img"; //url where icons for uplod are stored - no trailing slash
//******* END SETTINGS ********************//
include_once( $root."/administrator/components/com_jmusic/config.jmusic.php");
$path_image = $root.$cin_pathimages."/";
$path_thumb = $root.$cin_paththumbs."/";
$dir = $host.$cin_pathimages."/";
$file = $_FILES['file'];
if ((($file["type"] == "image/png")||($file["type"] == "image/jpeg"))){
if($file["size"] > ($up_size * 1024)){
echo "<img src ='{$icons}/error.gif'> Filesize ".($file["size"] / 1024) ." Kb is too big. Allowable upload size is {$up_size} KB - Please upload a smaller one";
} else {
if ($file["error"] > 0){
echo "<img src ='{$icons}/error.gif'>Return Code: ".$file["error"]."<br />";
} else {
if ($file["type"] == "image/png"){
$file['name'] = time().rand().".png";
} else {
$file['name'] = time().rand().".jpg";
}
if(!is_file($dir.$file['name'])){
echo "No existe el archivo";
move_uploaded_file($file["tmp_name"], $path_image.$file["name"]);
resize_image($path_image.$file["name"], $path_thumb."tn_".$file["name"], $cin_thumbwidth, $cin_thumbcreation, $cin_thumbquality);
resize_image($path_image.$file["name"], $path_image.$file["name"], $cin_ancho_imag, $cin_thumbcreation, $cin_thumbquality);
echo "<img src='".$host.$cin_paththumbs."/tn_".$file["name"]."' border='0' />";
} else {
echo "Si existe el archivo";
}
}
}
} else {
echo "<img src ='{$icons}/error.gif'> Invalid file";
}
?>
Como podria hacer para que una vez subida la imagen recuperar el nombre de esta y añadirlo al input:
<input class="inputbox" type="text" name="imgfilename" id="imgfilename" size="40" readonly="true" value="" />
Os agradeceria muchisimo alguan ayuda, he probado muchos metodos pero no consido naga. Saludos y gracias!!!