Android Question [RESOLVED] Upload 2 (two) files at a time using HTTP post

sangee

Member
Licensed User
Longtime User
Hello All...

I am exploring a way in which I can upload two or more files at once using the HTTP post. At present I am able to upload single file successfully using the code below...

B4X:
Dim job2 As HttpJob
            job2.Initialize(Filename,Me)
            job2.PostFile("http://myserver.com/uploadimg.php?filename=" & Filename,File.DirRootExternal & "/download/Images/", Filename)


Sub JobDone (Job As HttpJob)
Dim Filename As String
Dim Qstr As String
   'Log("JobName = " & Job.JobName & ", Success = " & Job.Success)
   
   If Job.Success = True Then
         Filename = Job.JobName
           File.Delete (File.DirRootExternal & "/download/Images/",Filename)
           Qstr = "DELETE FROM FilesToSend WHERE file = ?"
           SQL1.ExecNonQuery2(Qstr, Array As Object(Filename))               
   Else
         'Update DB
         Filename = Job.JobName
         'Qstr = "INSERT INTO FilesToSend (id, File, status) VALUES (NULL, '" & Filename & "','WAITING')"
         'SQL1.ExecNonQuery(Qstr)
         
         Qstr = "UPDATE FilesToSend SET status = ? WHERE file = ?"
         SQL1.ExecNonQuery2(Qstr, Array As Object("WAITING", Filename))
   End If

   Job.Release
End Sub

How can I achieve the option of uploading two files at once. My search in Google showed me some examples of uploading two files at once.The link below says PHP is capable of receiving multiple files.

http://php.net/manual/en/features.file-upload.multiple.php

I am trying this option because I have 1000s of small images to upload (each approx 10kb) and many posts in other forums suggested "Sending multiple images in a single package makes sense".

Also if some one has done such thing before can you please guide me the most efficient method of ensuring the file is uploaded to the server before deleting...

Thanks in Advance... :)

Regards,
Sangee
 

sangee

Member
Licensed User
Longtime User
Hello Erel.... I am receiving the files using PHP on Apache. I stumbled upon your tutorial on "Tutorial Android Http Multipart requests". I guess uploading 3 or 4 files at a time will be efficient than uploading all 1000+ images one by one. I cannot take the route of zipping all the files as I have to upload each image as soon as it is clicked by the student.

Can you please suggest me if doing multipart file upload is a good idea and if possible the server side PHP for receiving the files uploaded using the tutorial example will be very helpful. I am trying out on PHP but unfortunately I am unable to get the files uploaded ... the PHP file receiver I am using...

PHP:
<?php
if(isset($_FILES['files'])){

    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        echo "dabba . $file_name";
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];  
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }      
        //$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
        list($time, $date, $device) =  explode("_", $file_name);
      //check if folder exists for this device. If not create one.
      if(!file_exists('/vol/images/' . $device))
      {
        mkdir('/vol/images/' . $device);
        }
      //check if folder exists for this device on this date. If not create one.
      if(!file_exists('/vol/images/'. $device . '/' . $date))
      {
        mkdir('/vol/images/' . $device . '/' . $date);
        }      
        if(empty($errors)==true){      
            move_uploaded_file($file_tmp,'/vol/images/'.$device.'/'.$date.'/'.$file_name);
            //move_uploaded_file($file_tmp,'/vol1/archive/test/'.$file_name);
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        //echo $file_name;
        echo 'sucess';
    }
}
?>

The Android code I am using to make a multipart file upload... Can you please check where is this going wrong...


B4X:
                Dim files As List
                files.Initialize
              
                Dim FD As FileData
                FD.Initialize
                FD.Dir = File.DirRootExternal & "/download/Images/"
                FD.FileName = "00001.jpg"
                FD.KeyName = "files"
                FD.ContentType = "application/octet-stream"
                files.Add(FD)
              
            'Upload ready - First File
                Dim FD As FileData
                FD.Initialize
                FD.Dir = File.DirRootExternal & "/download/Images/"
                FD.FileName = "00001.jpg"
                FD.KeyName = "files"
                FD.ContentType = "application/octet-stream"
                files.Add(FD)

            'Upload ready - First File
                Dim FD As FileData
                FD.Initialize
                FD.Dir = File.DirRootExternal & "/download/Images/"
                FD.FileName = "00001.jpg"
                FD.KeyName = "files"
                FD.ContentType = "application/octet-stream"
                files.Add(FD)

            'Add name / values pairs (parameters)
                Dim NV As Map
                NV.Initialize
              
                NV.Put("files", "00001.jpg")
                NV.Put("files", "00002.jpg")  
                NV.Put("files", "00003.jpg")  
            Log("Uploading: " &  "00001.jpg" & " " & "00002.jpg" & " " & "00003.jpg")
            'Start the Upload
                Dim req As HttpRequest
                req = MultipartPost.CreatePostRequest("http://srv1.server.com/uploadimg2.php", NV, files)
                hc.Execute(req, 1)



Thanks Erel.
 
Upvote 0

sangee

Member
Licensed User
Longtime User
The tutorial post http://www.b4x.com/android/forum/threads/android-http-multipart-requests.8411/

Had to be modified like below and with the below server side PHP I could get the file(s) uploaded...

B4X:
                Dim files As List
                files.Initialize
               
                Dim FD As FileData
                FD.Initialize
                FD.Dir = File.DirRootExternal & "/download/Images/"
                FD.FileName = Filename1
            'Note the square brackets in the keyname files. The PHP expects this.
                FD.KeyName = "files[]"
                FD.ContentType = "application/octet-stream"
                files.Add(FD)
               
            'Upload ready - First File
                Dim FD As FileData
                FD.Initialize
                FD.Dir = File.DirRootExternal & "/download/Images/"
                FD.FileName = Filename2
            'Note the square brackets in the keyname files. The PHP expects this. The original post is not showing this :-(
                FD.KeyName = "files[]"
                FD.ContentType = "application/octet-stream"
                files.Add(FD)


            'Add name / values pairs (parameters)
                Dim NV As Map
                NV.Initialize
               
                NV.Put("filesa", Filename1)
                NV.Put("filesb", Filename2)   
            'Log("Uploading: " &  Filename1 & " " & Filename2 )

            'Start the Upload
                Dim req As HttpRequest
                req = MultipartPost.CreatePostRequest("http://srv1.server.com/uploadimg2.php", NV, files)
                hc.Execute(req, 1)
                UploadInProg = UploadInProg + 1

Now the PHP

PHP:
<?php
foreach ($_FILES["files"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["files"]["tmp_name"][$key];
        $name = $_FILES["files"]["name"][$key];
        move_uploaded_file($tmp_name, "data/$name");
    }
}
?>
 
Upvote 0
Top