Android Save SD Card file to Remote server using PHP

In the previous post I explained about listing the specific extension files in Android list view. Now lets have a look to upload the file to remote server using a server side coding in PHP

private String SaveFileToServer() {
    String serverurl ="http://example.com/uploadfile.php"; // this is your server url to which you post the file contents
    String fileurl = "absolute_path_to_file_stored_on_sd_card"; // the path should be absoulute starting with /mnt/sdcard/filename.doc etc
  
    try {
      FileInputStream fis = new FileInputStream(new File(fileurl));
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] buf = new byte[1024];
      try {
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
        bos.write(buf, 0, readNum); // no doubt here is 0
      }
   } catch (IOException ex) {
      ex.printStackTrace();
 }
 byte[] bytes = bos.toByteArray();
 byte[] filetosend = Base64.encode(bytes, Base64.DEFAULT);
 String fts = new String(filetosend);
 this.user.setBase_64_encoded_filestring(fts);
 String parameters = this.user.tofileString();
 try {
   this.message = ServerCommunication.post_string(serverurl, parameters); // this is custom function to post the data to post the remote url
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
 }
} catch (FileNotFoundException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
return this.message;
 }
}

After this lets have a look at server side php code that will accept the data save on server and in return give you full path for the file saved

<?php 
if(isset($_POST['filedata'])) $filedata=$_POST['filedata']; else $filedata=""; // check for filedata to save
if(isset($_POST['file_url'])) $filename=$_POST['file_url']; else $filename=""; // check for filename not empty
$filename=date("ymdhis")."-".$fname;// change the filename to append the timestamp to avoid overwrite
$location="../../files/".$filename;// decide the location
//now write the file
 $filedata1=base64_decode($filedata);
 $ftw=fopen($location,'wb');
 if(fwrite($ftw,$filedata1)) {
 $fileurl="http://www.example.com/files/".$filename;
 echo $fileurl;
 } 
 
 fclose($ftw);
 ?>

So on success it will give you full path as output which you can save in your ANDROID code for future refecence

The code was simple but I have done some modifications as per the requirement. Hope you find this useful, ENJOY the stuff.

Advertisements