2017-01-20 115 views
1

我想嘗試使用php和mysql上傳圖像。我正在使用表單使用ajax發送數據。使用ajax上傳圖像mysql php

我的HTML代碼:

<input type="file" name="logo" id="logo" class="styled"> 
<textarea rows="5" cols="5" name="desc" id="desc" class="form-control"></textarea> 
<input type="submit" value="Add" id="btnSubmit" class="btn btn-primary"> 

Ajax代碼:

var formData = new FormData($("#frm_data")[0]); 
$("#btnSubmit").attr('value', 'Please Wait...'); 
$.ajax({ 
    url: 'submit_job.php', 
    data: formData, 
    cache: false, 
    contentType:false, 
    processData:false, 
    type: 'post', 
    success: function(response) 

我的PHP代碼(submit_job.php):

$desc = mysqli_real_escape_string($con, $_POST['desc']); 
$date = date('Y-m-d H:i:s'); 
$target_dir = "jobimg/"; 
$target_file = $target_dir . basename($_FILES["logo"]["name"]); 
move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file); 

回答

1

試試這個:

jQuery的:

$('#upload').on('click', function() { 
     var file_data = $('#pic').prop('files')[0]; 
     var form_data = new FormData(); 
     form_data.append('file', file_data); 

     $.ajax({ 
       url   : 'upload.php',  // point to server-side PHP script 
       dataType : 'text',   // what to expect back from the PHP script, if anything 
       cache  : false, 
       contentType : false, 
       processData : false, 
       data  : form_data,       
       type  : 'post', 
       success  : function(output){ 
        alert(output);    // display response from the PHP script, if any 
       } 
     }); 
     $('#pic').val('');      /* Clear the file container */ 
    }); 

PHP的:

<?php 
    if ($_FILES['file']['error'] > 0){ 
     echo 'Error: ' . $_FILES['file']['error'] . '<br>'; 
    } 
    else { 
     if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name'])) 
     { 
      echo "File Uploaded Successfully"; 
     } 
    } 

?> 
+0

move_uploaded_file(jobimg /橫幅_pipe-_puzzle.png):未能打開流:C中沒有這樣的文件或目錄:\ WAMP \ www \ jobPortalplus \ Admin \ submit_job.php在線37 –

+0

完成,謝謝。它的工作 –

+0

但我也想在數據庫中存儲圖像名稱。如何讓我的圖像名稱變量 –

0
<script type="text/javascript"> 
    $(document).ready(function() { 
     $("form").submit(function (event) { 
      event.preventDefault(); 
      var formdata = new FormData($('form')[0]); 
      var url = $("form").attr('action'); 
      $.ajax({ 
       url: url, 
       type: "POST", 
       data: formdata, 
       dataType: "json", 
       processData: false, 
       contentType: false, 
       success: function (data) { 
        console.log(data); 
       } 
      }); 
     }); 
    }); 
</script>