차근차근/Android

Upload an Image to a PHP Scrip( phonegap 카메라로 사진 찍어서 올리기)

예쁜꽃이피었으면 2014. 8. 21. 15:34

http://blog.naver.com/kjy1973snu?Redirect=Log&logNo=140128849562


<meta charset="utf-8" />

Upload an Image to a PHP Script

Page historylast edited by camdagr8 4 days ago

Uploading an image is pretty simple. Here's a snippet on how to do it.

 

JavaScript

 


<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Image</title>

<link rel="stylesheet" href="/jquery.mobile-1.0a1.min.css" /> 

<script type="text/javascript" charset="utf-8" src="phonegap-0.9.3.js"></script>
<script src="jquery-1.4.3.min.js"></script> 
<script src="jquery.mobile-1.0a1.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 function sendImage(src) {
  
  // Set the image source [library || camera]
  src = (src == 'library') ? Camera.PictureSourceType.PHOTOLIBRARY : Camera.PictureSourceType.CAMERA;
  
  // Aquire the image -> Phonegap API
  navigator.camera.getPicture(success, fail, {quality: 45, sourceType: src});
  
  // Successfully aquired image data -> base64 encoded string of the image file
  function success(imageData) {
   var url = 'http://www.mysite.com/API/mobileImageUpload.php';
   var params = {image: imageData};
   
   // send the data
   $.post(url, params, function(data) {
    
    // Display the selected image on send complete
    $('#image').attr('src', 'data:image/jpeg;base64,' + params['image']);
    
   });
  }
  
  function fail(message) { alert(message); }
 }
 
 $('.send-image').click(function () { sendImage($(this).val()); }); 
});

</script>
</head>

<body>
    <p>
        <img style="width:60px; height:60px" id="image" src="" />
    </p>
    <p>
        <input type="button" class="send-image" value="camera" />
        <input type="button" class="send-image" value="library" />
    </p>
</body>
</html>

 

 

 

 

PHP Script


<?php 

if ($_REQUEST['image']) {
 
 // convert the image data from base64
 $imgData = base64_decode($_REQUEST['image']);
 
 // set the image paths
 $file = '/uploads/' . md5(date('Ymdgisu')) . '.jpg';
 $url = 'http://www.mysite.com' . $file; 
 
 // delete the image if it already exists
 if (file_exists($file)) { unlink($file); }
 
 // write the imgData to the file
 $fp = fopen($file, 'w');
 fwrite($fp, $imgData);
 fclose($fp);
}

?>

 

 


반응형