2014-12-03 207 views
3

我試圖上傳圖像與jQuery和Ajax功能,以及如何獲取圖像文件的所有細節,比如在PHP中,我們使用$_FILE()如何在codeigniter中使用ajax上傳圖片?

這裏是我的代碼

JS

$("#uploadimg").click(function() { 
    $("#file").click(); 
}); 

$("#file").change(function(e) { 
    var file=$('#file').val(); 
    alert(file); 
    die(); 
    e.preventDefault(); 
    $.ajax({ 
     url:'http://localhost/JSG/blog/uploadimg', 
     secureuri:false, 
     type: "POST", 
     fileElementId:'image', 
     dataType: 'text', 
     data:{ file: file }, 
     cache: true, 
     success: function (data){ 
      alert(data); 
      console.log(data); 
     }, 
    }); 
}); 

控制器

public function uploadimg() 
{ 
    $var = $_POST['file']; 
    print_r($var); 
    if($this->input->post('file')) { 
     $config['upload_path'] = 'upload'; 
     $config['file_name'] = $var; 
     $config['overwrite'] = 'TRUE'; 
     $config["allowed_types"] = 'jpg|jpeg|png|gif'; 
     $config["max_size"] = '1024'; 
     $config["max_width"] = '400'; 
     $config["max_height"] = '400'; 
     $this->load->library('upload', $config); 

     if(!$this->upload->do_upload()) { 
      $this->data['error'] = $this->upload->display_errors(); 
      print_r($this->data['error']); 
     } else { 
      print_r("success"); 
     } 
    } 
} 

查看

<form role="form"> 
    <div class="form-group"> 
     <label for="recipient-name" class="control-label">Blog Title:</label> 
     <input type="text" class="form-control" id="recipient-name"> 
    </div> 
    <div class="form-group"> 
     <label for="message-text" class="control-label">Message:</label> 
     <textarea class="form-control" id="message-text"></textarea> 
    </div> 
    <div class="form-group"> 
     <label for="message-text" class="control-label">Upload image:</label> 
     <img src="<?php echo base_url();?>assest/img/blank.png" alt="Blank image" id="uploadimg" class="img-thumbnail"> 
     <input style="display:none" id="file" value=" " type="file" class="file" data-show-preview="false"> 
    </div> 
</form> 

響應

C:\fakepath\Koala.jpg You did not select a file to upload.

請幫

回答

8

您可以使用FORMDATA API在HTML5上傳文件。

您的形式必須是:

<form enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="formname" method="post" action=""> 

然後jQuery的:

function uploadImage() { 

    if (typeof FormData !== 'undefined') { 

     // send the formData 
     var formData = new FormData($("#formID")[0]); 

     $.ajax({ 
      url : baseUrl + 'uploadImage', // Controller URL 
      type : 'POST', 
      data : formData, 
      async : false, 
      cache : false, 
      contentType : false, 
      processData : false, 
      success : function(data) { 
       successFunction(data); 
      } 
     }); 

    } else { 
     message("Your Browser Don't support FormData API! Use IE 10 or Above!"); 
    } 
} 

然後在控制器中你會得到$_FILES陣列的文件。

+0

當我在我的控制器中使用$ _FILES他扔[Object FileData] 有一些問題..請幫助 – Secure 2014-12-04 12:08:40

+1

我沒有得到實際值如何使用完整的文件路徑。 – Secure 2014-12-04 12:59:35

+0

您必須檢查 - $ _FILES ['name']其中'name'是輸入類型=文件的名稱。您還必須爲所有輸入提供名稱屬性。使用var_dump()來查看信息。 – John 2014-12-04 13:44:14

0

在視圖在您展示形式:

附加屬性:enctype=multipart/form-data

或者,

如果要創建與表單輔助形式:

<?php echo form_open_multipart('blog/uploadimg');?> 
+0

不,我沒有使用表單標籤。 這裏是我的看法 - >>>>>

Blank image
Secure 2014-12-03 11:18:25

+0

嘿請給我一些解決方案.. – Secure 2014-12-03 12:35:11

0

,如果你在JavaScript中使用這個插件(寫得很好),你可以得到無縫的功能。

http://malsup.com/jquery/form/

在PHP

<?php 
$target_dir = "uploads/"; 
$target_file = $target_dir . basename($_FILES["file"]["name"]); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
// Check if image file is a actual image or fake image 
if(isset($_POST["submit"])) { 
    $check = getimagesize($_FILES["file"]["tmp_name"]); 
    if($check !== false) { 
     echo "File is an image - " . $check["mime"] . "."; 
     $uploadOk = 1; 
    } else { 
     echo "File is not an image."; 
     $uploadOk = 0; 
    } 
} 
// Check if file already exists 
if (file_exists($target_file)) { 
    echo "Sorry, file already exists."; 
    $uploadOk = 0; 
} 
// Check file size 
if ($_FILES["file"]["size"] > 500000) { 
    echo "Sorry, your file is too large."; 
    $uploadOk = 0; 
} 
// Allow certain file formats 
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" 
&& $imageFileType != "gif") { 
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
    $uploadOk = 0; 
} 
// Check if $uploadOk is set to 0 by an error 
if ($uploadOk == 0) { 
    echo "Sorry, your file was not uploaded."; 
// if everything is ok, try to upload file 
} else { 
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) { 
     echo "The file ". basename($_FILES["file"]["name"]). " has been uploaded."; 
    } else { 
     echo "Sorry, there was an error uploading your file."; 
    } 
} 
?> 
+0

有沒有其他的選擇,在jquery上傳圖片? – Secure 2014-12-03 13:11:25

+0

爲什麼你在尋找另一個,如果這符合你的需求? – 2014-12-03 13:12:34

+0

我看到你的例子,但在這個例子中頁面刷新,但我不想在圖片上傳時刷新頁面。這就是爲什麼我使用jQuery – Secure 2014-12-03 13:23:57

0

您可以使用Ajaxfileupload.js上傳文件:

$('input[type="file"]').ajaxfileupload({ 
      'action': 'save_photo.php', 
      'params': { 
      'extra': 'info' 
      }, 
      'onComplete': function(response) { 

      console.log('custom handler for file:'); 
      alert(JSON.stringify(response)); 

      }, 
      'onStart': function() {    

      }, 
      'onCancel': function() { 
      console.log('no file selected'); 
      } 
    }); 

save_photo.php:

<?php 

print_r($_FILES); // print details about the file which has been uploaded 

?> 
+0

此API無法正常工作。當我使用此API時會顯示一些錯誤。 – Secure 2014-12-04 12:05:25

+0

這是完美的工作,我用過相同的..你有什麼錯誤? – 2014-12-04 12:25:09

+0

當我使用jquery.ajaxfileupload.js文件。我在控制檯中收到錯誤消息「Uncaught SyntaxError:Unexpected token <」 – Secure 2014-12-04 12:58:32