2015-09-05 4 views
0

Я пытаюсь загрузить файл в iFrame, пока все работает нормально, но я не могу обработать изображение в конце PHP, поскольку он, похоже, не получил его.Загрузить файл в iFrame

Кажется, что он загружается, хотя мой индикатор выполнения работает и показывает прогресс и завершает работу. ResponseText говорит: No image selected?

Вот мой АЯКС:

function submitFile() { 
    //The file location 
    var theFile = document.getElementById("image").files[0]; 
    var xhr = new XMLHttpRequest(); 
    //Disable submit button whilst upload is active 
    doc("submit").disabled = true; 

    //Completed 
    xhr.onload = function(e) { 
     if (this.status == 200) { 
      document.getElementById("imageUpload").innerHTML = xhr.responseText; 
      doc("submit").disabled = false; //Unlock submit button 
     } 
    }; 

    //Progress 
    xhr.upload.onprogress = function(e) { 
     if (e.lengthComputable) { 
      var currentPercentage = Math.round(e.loaded/e.total * 100); 
      document.getElementById("imageUpload").innerHTML = "UPLOAD IMAGE " + currentPercentage + "%"; 
      document.getElementById("imageUpload").style.backgroundSize = currentPercentage + "% 100%"; 
     } 
    }; 

    //Send data 
    xhr.open("POST", "php/uploadImage.php", true); 
    xhr.send(theFile); 
} 

Это форма, в которой я представляю изображение с, он будет загружать, когда я выбираю файл, однако, и не тогда, когда я нажимаю отправить see the onchange function.

<form action="php/submitMessage.php" onsubmit="validation(this)" method="post" id="submitMessage" enctype="multipart/form-data"> 
    <div class="left half"> 
     <input class="text" type="text" name="name" placeholder="First and Second Name" 
     rules="[A-Za-z]*\s[A-Za-z]*" /> 
     <input class="text" type="text" name="email" placeholder="Email Address" 
     rules="^[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" /> 
     <textarea name="message" placeholder="Enter your message here..." rows="5"></textarea> 
    </div> 
    <div class="right half"> 
     <input class="text" type="text" name="reg" placeholder="Car Registration"/> 
     <input type="file" onchange="submitFile();" name="image" id="image" style="display:none;" /> 
     <input type="hidden" name="image_location" id="image_location"/> 
     <label for="image" id="imageUpload" class="uploadBtn">Upload Image</label> 
     <p>Message will be regarded as a quote request if you provide an image.</p> 
    </div> 
    <input type="submit" id="submit" style="background-color:#fff;color:#000;" value="Submit Message/Quote" /> 
</form> 

Это мой PHP, я хочу, чтобы получить файл, изменить его размер, а затем установить переменную сеанса в его место, которое будет использоваться, когда остальная часть формы представляется как местоположение файла будет необходимо быть добавлен в строку базы данных.

<?php 
session_start(); 

//Image was selected 
if($_FILES['image']['tmp_name']) { 
    //any errors? 
    if(!$_FILES['image']['error']) { 
     //validate the file and setup future filename 
     $new_file = date("Ymdhisa"); 

     //Can't be larger than 5MB 
     if ($_FILES['image']['size'] > 5000000) { 
      //Resize the file 
      $width = 500; 

      //Keep aspect ratio 
      $size = getimagesize($_FILES['image']['tmp_name']); 
      $height = round($width*$size[1]/$size[0]); 

      //Create object 
      if ($size[2] == 1) { 
       $images_orig = imagecreatefromgif($_FILES['image']['tmp_name']); 
      } else if ($size[2] == 2) { 
       $images_orig = imagecreatefromjpeg($_FILES['image']['tmp_name']); 
      } else if ($size[2] == 3) { 
       $images_orig = imagecreatefrompng($_FILES['image']['tmp_name']); 
      } 

      //Get image size to create object 
      $photoX = imagesx($images_orig); 
      $photoY = imagesy($images_orig); 

      //Create resized object 
      $images_fin = imagecreatetruecolor($width, $height); 
      imagecopyresampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); //Resize the image 
      imagejpeg($images_fin,"images/".$new_images); //Save image to file 

      //Remove image from memory 
      imagedestroy($images_orig); 
      imagedestroy($images_fin); 

      //Set session key for file location 
      $_SESSION['tmp_image'] = "uploads/".$new_file; //Should be unset when message has been sent 
      $message = "File successfully uploaded!"; 
      echo $message; 
     } 
    } 
    else 
    { 
     $message = "There was an error: ".$_FILES['image']['error']; 
     echo $message; 
    } 
} else { 
    echo "No image selected?"; 
} 
?> 
+0

Возможный дубликат [Как отправить форму формы данных формы multipart/form-ajax (без jquery)?] (Http://stackoverflow.com/questions/5933949/ как-для-send-multipart-form-data-form-content-by-ajax-no-jquery) – Ferrybig

+0

@ferrybig, этот код не поддерживает отправку файлов. –

ответ

0

Это мой код, и его работа тоже хорошо мне, Надежда работать для вас слишком

function submitVisualMedia() 
 
      { 
 
       $(document).ready(function (e) { 
 
        var fd = new FormData($("#fileinfo")[0]); 
 
        $.ajax({ 
 
         url:, //YOUR DESTINATION PAGE 
 
         type: "POST", 
 
         data: fd, 
 
         enctype: 'multipart/form-data', 
 
         processData: false, // tell jQuery not to process the data 
 
         contentType: false, // tell jQuery not to set contentType 
 
         success: function() 
 
         { 
 
        //some code if you want 
 
    
 
         } 
 
        }); 
 

 

 
       }); 
 
       return false; 
 

 

 
      }
<form method="post" id="fileinfo" onsubmit='return submitVisualMedia()' > 
 
       <input class="form-control" type="text" id="title" > 
 
       <input class="form-control" type="file" name="visualMedia" id="visualMedia" accept="image/*"> 
 
       <button class="btn btn-success" type="submit">Upload</button> 
 
          </form>

и боковой PHP

public function uploadVisualMedia() { 

    ini_set('upload_max_filesize', '25M'); 
    ini_set('post_max_size', '25M'); 
    ini_set('max_input_time', 300); 
    ini_set('max_execution_time', 300); 

    $fname = date('l-j-m-Y').'-'.rand(1,1000000); 
    $size = $_FILES['visualMedia']['size']; 
    $ftype = $_FILES['visualMedia']['type']; 
    $temp = $_FILES['visualMedia']['tmp_name']; 
    $type = array(); 
    $type = explode("/", $ftype); 
    $filename = "galleries/" . $type[0] . "_gallery/" . $fname . "." . $type[1]; 
    $index = 0; 
    while (file_exists($filename)) { 
     $filename = "galleries/" . $type[0] . "_gallery/" . $fname . "($index)" . "." . $type[1]; 
     $index++; 
    } 
    move_uploaded_file($temp, $filename); 

}

Вы больше всего меняете этот код, и он должен работать для вас хорошо. с этим вы также можете загрузить видео. измените имя файла на имя какой-либо папки.

+0

Я посмотрю, смогу ли я адаптировать свой код только к JavaScript, поскольку мне не нравится использовать jQuery. Спасибо, если я получу его работу из вашего примера, я приму свой ответ. –

+0

Кто-то проголосовал так, что было бы более полезно объяснить, что не так с вышеприведенным сообщением, поэтому я знаю, должен ли я следовать этому ответу или нет ... голосование вниз и не комментирование по существу бессмысленно ... lol –

Смежные вопросы