【问题标题】:Upload Image and insert in Database MySQl withAjax使用Ajax上传图像并插入数据库MySQl
【发布时间】:2014-03-11 12:03:37
【问题描述】:

我使用 JQuery mobile 和 PHP 和 Ajax 上传图像并将其插入数据库,但我在将图像名称插入数据库时​​遇到问题,数据库中的结果是:“C:fakepathLighthouse.jpg”,我上传后将只插入图像的名称。 php中的mu代码

      <?php // You need to add server side validation and better error handling here

     $data = array();

     if(isset($_GET['files']))
    {   
   $error = false;
   $files = array();
  £fichier=basename($file['name'];
   $uploaddir = 'photo/';
   foreach($_FILES as $file)

         {if(move_uploaded_file($file['tmp_name'], $uploaddir. $fichier)))                                                                                        
          {
                $files[] = $uploaddir .$file['name'];
        }
        else
        {
          $error = true;
          }
               }
            $data = ($error) ? array('error' => 'There was an error uploading your                                   files') : array('files' => $files);
                 }
        else
        {
   $data = array('success' => 'Form was submitted', 'formData' => $_POST);
         } 

      echo json_encode($data);

        ?>

我的代码脚本:

        $(function()
        {
// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);
$('form').on('submit', uploadFiles);

// Grab the files and set them to our variable
function prepareUpload(event)
{
    files = event.target.files;
}

// Catch the form submit and upload the files
function uploadFiles(event)
{
    event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

    // START A LOADING SPINNER HERE

    // Create a formdata object and add the files
    var data = new FormData();
    $.each(files, function(key, value)
    {
        data.append(key, value);
    });

      $.ajax({
        url: 'submit.php?files',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server   its a query string request
         success: function(data, textStatus, jqXHR)
          {
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
                submitForm(event, data);
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
            // STOP LOADING SPINNER
        }
    });
       }

   function submitForm(event, data)
  {
    // Create a jQuery object from the form
    $form = $(event.target);

    // Serialize the form data
    var formData = $form.serialize();

    // You should sterilise the file names
    $.each(data.files, function(key, value)
    {
        formData = formData + '&filenames[]=' + value;
        console.log('nom de l image:' + '&filenames[]=' + value);
    });

    $.ajax({
        url: 'submit.php',
        type: 'POST',
        data: formData,
        cache: false,
        dataType: 'json',
        success: function(data, textStatus, jqXHR)
        {
            if(typeof data.error === 'undefined')
            {
                // Success so call function to process the form
                console.log('SUCCESS: ' + data.success);
            }
            else
            {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            // Handle errors here
            console.log('ERRORS: ' + textStatus);
        },
        complete: function()
        {
            // STOP LOADING SPINNER
        }
    });
}
   });

我的初始页面(index.html)

function getLocation(){
  if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
 } 
 //Get the latitude and the longitude;
  function successFunction(position) {


     var latt = position.coords.latitude;
   var lngg = position.coords.longitude;
var nom=$('input[id=nom]').val();
var photo= $('input[id=file_upload]').val();
var ville= $('input[id=ville]').val();
var pays= $('input[id=pays]').val();
long.value="Longitude: " + lngg;
   lat.value="Latitude: " + latt;

//var adr="Sousse";
codeLatLng(latt, lngg);
// var adresse=codeLatLng(latt, lngg);

  var sendAjax = $.ajax({
    type: "POST",
    url: 'api.php?rquest=insertMosque',
   data:   'lat='+latt+'&lng='+lngg+'&nom='+nom+'&pays='+pays+'&ville='+ville+'&photo='+photo,
    success: handleResponse
  });

  function handleResponse(){
  $('#answer').get(0).innerHTML = sendAjax.responseText;
  //console.log(data);
  }

}

function errorFunction(){
  alert("Geocoder failed");
}
}



code api.php
   private function insertMosque() {
    if ($this->get_request_method() != "POST") {
        $this->response('', 406);
    }

    $nom = $_POST['nom'];
    $lat =($_POST['lat']);
 $lng = $_POST['lng'];
 $adr = $_POST['adr'];
 $ville = $_POST['ville'];
          $pays = $_POST['pays'];

$photo=$_POST['photo'];
       //$photo =  addslashes($file['name']);

    $query = mysql_query("INSERT INTO mosque VALUES('', '$nom', '$lng','$lat',' $photo','$adr','$ville','$pays')", $this->db);
    if ($query) {
        $data['success'] = 'Insertion avec success';
    } else {
        $data['errors'] = 'failed';
    }
    $this->response($this->json($data), 200);
  }

【问题讨论】:

  • 我不完全确定您的问题是什么。你想只上传上传照片的文件名而不是文件路径吗?请澄清一下,也许可以举例说明您的预期行为。
  • 我想在数据库(Mysql)中插入图片的文件名

标签: php jquery html ajax jquery-mobile


【解决方案1】:

您可以使用 api.php 中的 explode 函数来解析您从 POST 获取的文件路径:

$nom = $_POST['nom'];
$lat =($_POST['lat']);
$lng = $_POST['lng'];
$adr = $_POST['adr'];
$ville = $_POST['ville'];
$pays = $_POST['pays'];

//for example, say $_POST['photo'] = "C:/my/fake/directory/testfile.jpg"
$photopath = explode("/", $_POST['photo']);

//print_r($photopath) results in Array ( [0] => C: [1] => my [2] => fake [3] => directory [4] => testfile.jpg )

$photo = end($photopath); //gets last result in the array (your filename)

$query = mysql_query("INSERT INTO mosque VALUES('', '$nom', '$lng','$lat',' $photo','$adr','$ville','$pays')", $this->db);

请注意,这可能不是从路径获取文件名的最有效方法,并且您的分隔符(上例中的"/")可能需要根据您获取路径的方式进行更改。如果您有任何问题,请随时提出。

【讨论】:

    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    相关资源
    最近更新 更多