2015-01-16 200 views
1

我想用ajax上传文件。通过ajax上传文件

form enctype="myltipart/form-data" id="pastTest-form" method="POST" action="upload.php"> 
      <div class="feedback-form-inputs col-5"> 
       <div class="input-field"> 
        <select id="type" required> 
         <option value="quiz">Quiz</option> 
         <option value="midterm">Midterm</option> 
         <option value="final">Final</option> 
        </select> 
       </div> 
       <div class="input-field"> 
        <input type="text" id="professor"/> 
       </div> 
       <div class="input-field"> 
        <input type="text" id="name"/> 
       </div> 
       <div class="input-field"> 
        <input type="file" id="uploaded_file" name="file" accept="" required /> 
       </div> 
      </div><!-- END feedback-form-inputs --> 
      <div class="clear"></div> 
       <input type="submit" value="submit" onclick="submit() /> 
       <div id="upload-status"> </div> 
      </form> 

我的打开ajax的函数在外部文件中。

function addPastTest1(cid){ 
    // form variables 
    var type = _("type").value; 
    var professor = _("professor").value; 
    var name = _("name").value; 

    var fileSelect = _('uploaded_file'); 
    var status = _('upload-status'); 
    event.preventDefault(); 
    // Update status text. 
    status.innerHTML = 'Uploading...'; 
    // Get the selected files from the input. 
    var file = fileSelect.files[0]; 

    var FileName = file.name; 
    var FileSize = file.size; 
    var allowed = ["msword", "pdf","pages"]; 
    var found = false; 
    // check if the extension of the file match the allowed ones 
    allowed.forEach(function(extension) { 
     if (file.type.match('application/'+extension)) { 
      found = true; 
     } 
    }) 
    if (FileSize >10204){ 
     status.innerHtml = 'File must be less than 1mb in size'; 
    } 
    if (found==true){ 
     // Create a new FormData object. 
     var formData = new FormData(); 
     // Add the file to the request. 
     formData.append('file', file, FileName); 
     // Set up the request. 
     var ajax = ajaxObj("POST", "ajaxResponse.php"); 
     ajax.onreadystatechange = function(){ 
      if (ajaxReturn(ajax)==true){ 
       if (ajax.responseText=='failed'){ 
       status.innerHtml = "failed to upload file"; 
       } 
       else { 
        status.innerHtml = 'uploaded'; 
        alert(ajax.responseText); 
       } 
      } 
     } 
     ajax.send(formData);   //ajax.send("f="+formData+"&t="+type+"&p="+professor+"&n="+name+"&cid="+cid+"&fn="+FileName); 
    } 
} 

所以我发送formData到php。但此时我无法从表单数据中提取文件并将其上传到服务器。 这里是我的PHP

// Ajax calls this code to add a past test 
if (isset($_FILES['file']){ 
    $file = $_FILES['file']; 
      $path = 'files/'.$type.'/'.$fileName; 
      $moveResult = move_uploaded_file($file, $path); 

     if ($moveResult != true) { 
      echo "ERROR: File not uploaded. Try again."; 
      //unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
      exit(); 
     } 


    $path = 'files/'.$type.'/'.$fileName; 
    $sql = "INSERT into past_papers VALUES ('$name', '$type', '$cid', '$professor','$path')"; 
    $query = mysqli_query($db_conx,$sql); 
    if (mysqli_affected_rows($db_conx)>0){ 
     echo "success"; 
     exit(); 
     } 
    else { 
     echo "failed sql"; 
     exit(); 
    } 
} 
?> 

我也想抓住与文件的输入和共同处理它们。上传文件,并将输入插入数据库。

+0

您应该使用搜索功能,吨后都与此有关,例如 HTTP ://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchr rq = 1 也 http://stackoverflow.com/search?q=php+ajax+upload –

+1

您的上传处理是完全无效的。你需要检查'$ _FILES ['file'] ['error']'** FIRST **,以查看上传是否被巧妙执行并成功。你只是假设什么都不会出错,这是完全错误的。 –

回答

0

我能找到的最简单的一个。 :)

jQuery代码

$("#form-id").on('submit',(function(e) { 
    e.preventDefault(); 
    $.ajax({ 
     url: "file-to-call.php", 
     type: "POST", 
     data: new FormData(this), 
     cache: false, 
     processData: false, 
     success: function(data) { 
      //handle success 
     } 
    }); 
})); 

HTML代码

<form name='form1' method='post' enctype='multipart/form-data' id='form-id'> 
    <input type='submit' id='input' value='Upload' /> 
</form>