Android Question Failed uploading image to online server

microbox

Active Member
Licensed User
Longtime User
Hi everyone...I getting no where with the application I'm working. I'm trying to upload image to the server but failed to do so. Kindly check my codes below.
ImageToSave is the variable that holds the converted image
B4X:
Sub Camera1_PictureTaken (Data() As Byte)

        camera1.StartPreview
        '-------------------------------------------------------------
        Dim fileName,pma,pmb As String
        DateTime.DateFormat = "yyyy-MM-dd"
        pma = DateTime.Date(DateTime.Now)
        DateTime.TimeFormat = "HH:mm"
        pmb = DateTime.Time(DateTime.Now)
        fileName = "Photo_" & TransId & pma &"_" & pmb
Try    
        '------------------------------------------------------------
        Dim out As OutputStream
        out = File.OpenOutput(File.DirRootExternal & "/" & AppFolder, fileName & ".jpg", False)
        out.WriteBytes(Data, 0, Data.Length)
        out.Close
    Dim im As Bitmap 
    im.Initialize(File.DirRootExternal & "/" & AppFolder,fileName & ".jpg")
    imgphoto.SetBackgroundImage(LoadBitmap(File.DirRootExternal & "/" & AppFolder,fileName & ".jpg"))
    Log("Image saved: " & File.Combine(File.DirRootExternal & "/" & AppFolder, fileName & ".jpg"))
    File1 = File.DirRootExternal & "/" & AppFolder
    File2 = fileName & ".jpg"
    btnCamera.Enabled = True
    Dim bytes() As Byte =  ImageToBytes(im)
    Dim B64 As Base64
    ImageToSave=""
    ImageToSave = B64.EncodeBtoS(bytes,0,bytes.Length-1)
    Log(ImageToSave.Length)
    
Catch
Log("Camera error")
End Try
End Sub

The next block of code is sending to the server
B4X:
Sub btnsendImages_Click
    Dim loginServer As HttpJob
    loginServer.Initialize("SubmitImage",Me)
    loginServer.Download2("http://" & ServerIP,    Array As String("action","SubmitImage","photo",ImageToSave,"rep_id",Rep_Id))
End Sub
The total length of ImageToSave is 1957536 and I'm getting a "414 Request-URI Too long". I read from forum that with this kind of case it is best to use POST. Can any one help me point in the right direction how to resolve my trouble?

Best regards,
microbox
 

DonManfred

Expert
Licensed User
Longtime User
Try it like this
B4X:
    Dim j As HttpJob
    j.Initialize("",Me)
    j.PostMultipart("https://domain.com",CreateMap("action":"SubmitImage","rep_id":Rep_Id,"photo":ImageToSave),Null)
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Dim res As String = j.GetString()
        Log(res)
    Else
        Log(j.ErrorMessage)
    End If
    j.Release
 
Upvote 0

microbox

Active Member
Licensed User
Longtime User
Try it like this
B4X:
    Dim j As HttpJob
    j.Initialize("",Me)
    j.PostMultipart("https://domain.com",CreateMap("action":"SubmitImage","rep_id":Rep_Id,"photo":ImageToSave),Null)
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Dim res As String = j.GetString()
        Log(res)
    Else
        Log(j.ErrorMessage)
    End If
    j.Release
Hi Don thanks for the time, I tried but I'm having this error message
B4X:
ResponseError. Reason: javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x79320858: Failure in SSL library, usually a protocol error
error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version (external/openssl/ssl/s23_clnt.c:744 0x73edfcfc:0x00000000), Response:
javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x79320858: Failure in SSL library, usually a protocol error
error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version (external/openssl/ssl/s23_clnt.c:744 0x73edfcfc:0x00000000)
 
Upvote 0

JohnC

Expert
Licensed User
Longtime User
Hi, in the sample code you provided, you used "http". But Don's suggested code used "https".

The second error you reported was related to SSL, so maybe you accidently used "https" when using Don's sample and maybe that error is due to the remote website not supporting SSL.

If so, then maybe try Don's code but use http instead of https?
 
Last edited:
Upvote 0

microbox

Active Member
Licensed User
Longtime User
B4X:
Dim loginServer As HttpJob
loginServer.Initialize("SubmitImage",Me)
loginServer.PostMultipart("http://" & ServerIP,CreateMap("action":"SubmitImage","rep_id":Rep_Id,"photo":ImageToSave),Null)
Wait For (loginServer) JobDone(loginServer As HttpJob)
    If loginServer.Success Then
        Dim res As String = loginServer.GetString()
        Log(res)
    Else
        Log(loginServer.ErrorMessage)
    End If
    loginServer.Release

when I change https:// to http:// do not gives the ssl error but
log(res) --> gives out NULL
 
Upvote 0

microbox

Active Member
Licensed User
Longtime User
@JohnC thanks :)

here is my code in the php file
B4X:
 case "SubmitImage":
        $id = $_GET["rep_id"]; < -- not sure if this is right.
        $photo = $_GET["photo"]; < -- same.
      
        $q = mysqli_query($con,"Insert into t_photos(rep_id,image)values('$id','$photo')");
         if ($con->query($q) === True) {
            echo "SuccessSavingImage";
            } else {
                echo "Failed to save" . $conn->error;
            }
        break;
 
Upvote 0

JohnC

Expert
Licensed User
Longtime User
when I change https:// to http:// do not gives the ssl error but
log(res) --> gives out NULL
You have a "Log()" line of code for both Success = true or false, so when you say it is reporting NULL, which branch was reporting this (Succeed=True or False branch)?

I'm not a PHP expert, but the code Don provided I believe should work, so I would think the issue is in the PHP if it still doesn't work.
 
Last edited:
Upvote 0

drgottjr

Expert
Licensed User
Longtime User
loginServer.Download2("http://" & ServerIP, Array As String("action","SubmitImage","photo",ImageToSave,"rep_id",Rep_Id))
The total length of ImageToSave is 1957536 and I'm getting a "414 Request-URI Too long". I read from forum that with this kind of case it is best to use POST. Can any one help me point in the right direction how to resolve my trouble?

just so you understand, there are 2 issues:
1) ImageToSave is a string of bytes 1957536 bytes in length. the URI cannot be longer than 2048 bytes. hence the error.
2) furthermore, even if ImageToSave was very small, your Download2() may not have worked. The server may have been expecting a post, not a get (which is what download2() is. and it stands to reason that if the upload involves an image, there is really no way you could use download() and expect it to be a legal URI.

you're getting help with post, and i'm sure it will work out for you, but i just wanted to make sure you understand the importance of giving the server what it's expecting and the way in which it's expecting it.
 
Upvote 0

JohnC

Expert
Licensed User
Longtime User
Any chance you can post the B4A "sending" code and the PHP "receiving" code so it can be helpful to others who are looking for a similar solution?
 
Upvote 0

microbox

Active Member
Licensed User
Longtime User
Hi..I'm sorry it took me awhile to post this...was busy some other things. :) and I apologize if my prototype code is not totally cleaned.
Section For the PHP (Receiving)
PHP:
<?php
error_reporting(0);
$host = "localhost";
$user = "root";
$pw = "";
$db = "empprofilr";

$con = mysqli_connect($host,$user,$pw) or die(mysql_error());
mysqli_select_db($con,$db) or die(mysqli_error());
mysqli_query($con,"SET CHARACTER SET utf8");
mysqli_query($con,"SET NAMES 'utf8'");

$action = $_GET["action"];
switch ($action)

{
    case "SaveImage":
        $photo = $_GET["image"];
        $q = mysqli_query($con,"Insert into employees(name,img)values('Test','$photo')");
         if ($con->query($q) === TRUE) {
            echo "Error Saving";
        } else {
            echo "SuccessSave" . $conn->error;
        }
     
    break;
    default:
        die("NULL");

}
?>

This is for the taking picture and converting it.
B4X:
Sub Camera1_PictureTaken (Data() As Byte)
        camera1.StartPreview
        Dim fileName,pma,pmb As String
        DateTime.DateFormat = "yyyy-MM-dd"
        pma = DateTime.Date(DateTime.Now)
        DateTime.TimeFormat = "HH:mm"
        pmb = DateTime.Time(DateTime.Now)
        fileName = "Photo_" & TransId & pma &"_" & pmb
Try  
       
        '------------------------------------------------------------
        Dim out As OutputStream
        out = File.OpenOutput(File.DirRootExternal & "/" & AppFolder, fileName & ".jpg", False)
        out.WriteBytes(Data, 0, Data.Length)
        out.Close
    Dim im As Bitmap
    im.Initialize(File.DirRootExternal & "/" & AppFolder,fileName & ".jpg")
    imgphoto.SetBackgroundImage(LoadBitmap(File.DirRootExternal & "/" & AppFolder,fileName & ".jpg"))
    Log("Image saved: " & File.Combine(File.DirRootExternal & "/" & AppFolder, fileName & ".jpg"))
    File1 = File.DirRootExternal & "/" & AppFolder
    File2 = fileName & ".jpg"
    btnCamera.Enabled = True
        ImageToSave = Base64Con.EncodeFromImage(File1,File2)
        Log("File Saved")
        Msgbox("File saved!","Test It")
Catch
Log("Camera error")
End Try
End Sub

This part is to send to the PHP
B4X:
Sub btnsendImages_Click
    Dim loginServer As HttpJob
    loginServer.Initialize("SubmitImage",Me)
'    loginServer.Download2("http://" & ServerIP ,    Array As String("action","SubmitImage","photo",ImageToSave,"rep_id",Rep_Id))
    loginServer.PostMultipart("http://" & ServerIP,CreateMap("action":"SubmitImage","rep_id":Rep_Id,"photo":ImageToSave.Trim),Null)
    Wait For (loginServer) JobDone(loginServer As HttpJob)
    If loginServer.Success Then
        Dim res As String = loginServer.GetString()
        If res.Contains("SuccessSavingImage") Then
            Log("Image and id saved!")  
        End If
    Else
        Log(loginServer.ErrorMessage)
    End If
    loginServer.Release
End Sub
 
Upvote 0
Top