Cross-platform SDK and HTML5 tools for mobile app development
X
 
23 posts / 0 new
Last post
Davide Mari
DavidSeas's picture
Offline
Mobile Conjurer
Joined: 10 May 2012
Posts:
Send Image using http post

 

Hi,

I'm using http functions and classes to send some data to a remote server. If I use write() function with a string all works fine but when I use writeFromData() function to send an image, I get the error: Mosync 40001. 

This is the source code:

void LoginScreen::initiateConnection(const char* url)

{

if(mIsConnected)

{

mLog->setText("2");

printf("already connected\n..");

return;

}

mLog->setText("3");

printf("\nconnecting to %s", url);

int res = mHttp.create(url, HTTP_POST);

if(res < 0)

{

printf("unable to connect - %i\n", res);

}

else

{

//mHttp.finish();

mLog->setText("4");

mIsConnected = true;

mHttp.setRequestHeader("Content-Length", "11");

mHttp.setRequestHeader("Content-Type", "text/plain; charset=utf-8");

mHttp.setRequestHeader("Content-Language","it-IT");

 

//mUserInstructions->setText("Connesso");

//mPassInstructions->setText("Connesso");

mHttp.writeFromData(SPLASH_NOLOGO, 0, maGetDataSize(SPLASH_NOLOGO));

}

 

}

SPLASH_NOLOGO is a png file inserted in resource file
I read that 40001 is a problem with resource file but the SPLASH_NOLOGO handle is correctly inserted because I use it as background image.
I also tried to send the image obtained after a snapshot (as in CameraDemo example) but the problem is the same.

There is a particular way to use writeFromData or in general to send images?

Thanks for your help and work

Davide

kk
kk's picture
Offline
Joined: 7 Nov 2012
Posts:
after using

after using writeFromData(),my write operation is completed.The program control is then executing the connWriteFinished(),but in the server i didn,t get any image .

I tried using echo echo "Upload: " . $_FILES["file"]["name"] . "<br />";

echo "Type: " . $_FILES["file"]["type"] . "<br />";

   echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
   echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
 
but all this $FILE values are coming NULL ........why is this happening ?......i have already posted my upload.php.....
 
Help me sam !
Thanx in Advance...
 
kk
kk's picture
Offline
Joined: 7 Nov 2012
Posts:
i tried your examples of

i tried your examples of uploading image to http server from link http://www.mosync.com/content/browse-local-image-directory-camera-and-allow-user-select-and-upload-server . this example working fine to upload image to http://www.mywebserver.com/imageupload.php server but for my upload.php  i am unable to upload image to server . i think i need to change my php file ...but i dont know  anything about php..so plz can you give me source of imageupload.php 

kk
kk's picture
Offline
Joined: 7 Nov 2012
Posts:
problem at uploading image to

problem at uploading image to server ..do i have to change my php file???

Sam Pickard
rival's picture
Offline
Mobile Archmage
Joined: 19 Mar 2009
Posts:
What is the error you get?

What is the error you get?

kk
kk's picture
Offline
Joined: 7 Nov 2012
Posts:
can anyone please tell me how

can anyone please tell me how to upload image to http server ....i tried a lot but still unable to upload image to http server . i am using android 2.3.3 api level 10.

this is my code :

#include <ma.h>

#include <mavsprintf.h>

#include <MAUtil/Moblet.h>

#include <MAUtil/String.h>

#include <MAUtil/Connection.h>

#include <MAUtil/FileLister.h>

#include <NativeUI/Widgets.h>

#include <NativeUI/WidgetUtil.h>

#include <conprint.h>

 

#define LOG printf

using namespace MAUtil;

 

using namespace NativeUI;

 

/**

 * Moblet to be used as a template for a Native UI application.

 */

class NativeUIMoblet : public Moblet, public HttpConnectionListener

{

public:

    /**

     * The constructor creates the user interface.

     */

    NativeUIMoblet() : mConn(this)

    {

        LOG("Confirmation - application started");

        mImageFile = maFileOpen("/mnt/sdcard/Image1352116968.jpg", MA_ACCESS_READ);

        LOG("Got image file handle %d", mImageFile);

        mEncodedImage = maCreatePlaceholder();

        maCreateData(mEncodedImage,maFileSize(mImageFile));

        LOG("Reading %d bytes to placeholder", maFileSize(mImageFile));

        int success = maFileReadToData(mImageFile, mEncodedImage, 0, maFileSize(mImageFile));

 

        if(success < 0)

        {

        LOG("Error - can't read file data");

        return;

        }

        LOG("Starting upload");

        if(mConn.isOpen())

        LOG("Connection open - aborting");

        else

        {

        mConn.create("http://www.myurl.com/upload.php/", HTTP_POST);

        char lenbuf[10];

        memset(lenbuf, 0, 10);

        sprintf(lenbuf, "%d", maGetDataSize(mEncodedImage));

        // mConn.setRequestHeader("Content-Type", "multipart/form-data");

        // mConn.setRequestHeader()

        mConn.setRequestHeader("content-length", lenbuf);

        mConn.writeFromData(mEncodedImage, 0, maGetDataSize(mEncodedImage));

       // mConn.write("Hello",5);

        }

 

  }

//http://www.mywebserver.com/imageupload.php

//http://dev.mosync.com/mobilelua/PhotoGallery/upload.php

    /**

     * Destructor.

     */

    virtual ~NativeUIMoblet()

    {

 

    }

 

    void keyPressEvent(int keyCode, int nativeCode)

    {

        if (MAK_BACK == keyCode || MAK_0 == keyCode)

        {

            // Call close to exit the application.

            close();

        }

    }

 

    /**

    * This method is called if the touch-up event was inside the

    * bounds of the button.

    * @param button The button object that generated the event.

    */

    virtual void buttonClicked(Widget* button)

    {

 

    }

    //http connection

    virtual void httpFinished(HttpConnection* http, int result)

    {

    if(result > 0)

    LOG("success finished");

    else

    LOG("unsuccess finished");

 

        LOG("Reading response");

        memset(mResponseBuffer, 0, 255);

        mConn.recv(mResponseBuffer, 254);

    }

 

    virtual void connectFinished(Connection* conn, int result)

    {}

 

    virtual void connRecvFinished(Connection* conn, int result)

    {

        if(result > 0)

            LOG(mResponseBuffer);

        else

        {

            LOG("Finished");

            mConn.close();

        }

    }

 

    virtual void connWriteFinished(Connection* conn, int result)

    {

    if(result > 0)

    LOG("write success");

    else

    LOG("write unsuccess");

        mConn.finish();

    }

 

    virtual void connReadFinished(Connection* conn, int result)

    {}

 

private:

 

    String mImagePath;

    HttpConnection mConn;

    MAHandle mImageFile;

    MAHandle mEncodedImage;

    char mResponseBuffer[255];

};

 

/**

 * Main function that is called when the program starts.

 */

extern "C" int MAMain()

{

    Moblet::run(new NativeUIMoblet());

    return 0;

}

and this my php file :
 
<?php
if($_FILES["file"]["size"] < 200000)
 {
 if ($_FILES["file"]["error"] > 0)
   {
   echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
   }
 else
   {
   echo "Upload: " . $_FILES["file"]["name"] . "<br />";
   echo "Type: " . $_FILES["file"]["type"] . "<br />";
   echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
   echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
 
   if (file_exists("upload/" . $_FILES["file"]["name"]))
     {
     echo $_FILES["file"]["name"] . " already exists. ";
     }
   else
     {
$sourcePath = $_FILES["file"]["tmp_name"];
$destiPath =  dirname(__FILE__).DIRECTORY_SEPARATOR."pranali/".$_FILES["file"]["name"];
 
var_dump($sourcePath);
var_dump($destiPath);
 
move_uploaded_file($sourcePath,$destiPath);
 
echo "file has been stored in" ; //$destiPath;
 
    
//move_uploaded_file($_FILES["file"]["tmp_name"],
      //dirname(__FILE__).DIRECTORY_SEPARATOR.$_FILES["file"]["name"]);
      //echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
 
     }
   }
 }
else
 {
 echo "Invalid file";
 }
?>
 
gerdodel
gerdodel's picture
Offline
Mobile Conjurer
Joined: 20 Mar 2012
Posts:
I got it! I have finally

I got it!

I have finally replicated the method used by the HTML browser to send files.
Noting with firebug as the browser builds the POST call, I have done the following:

//Take the picture. Very important: The data is in jpg format!
void TCamara::sacarFoto()
{
MAHandle h= maCreatePlaceholder();

maCameraSnapshot(this->formatoCamara, h);

//global handle defined in the moblet
this->ziudad->setFotoData(h);
}

//Send picture with more data
//Content-Type: multipart/form-data
//No base64 needed
void TNuevoZumbidoDatos::enviarZumbidoConImagen()
{
if (this->httpConnZumbido->create(this->urlServer, HTTP_POST)<0) msjError("Error");
else
{
String sENTER;
char * arrEnter=new char[2];
arrEnter[0]='\r';arrEnter[1]='\n';
sENTER.append(arrEnter,2);

String sAleatorio=integerToString(rand());
String sImagen="zmvl"+sAleatorio+".jpg";
String sHeaderBoundary="---------------------------"+sAleatorio;
String sBodyBoundary="--" + sHeaderBoundary+ sENTER;
String sBodyBoundaryEnd=sENTER + "--" + sHeaderBoundary +"--"+ sENTER;
this->datosZumbido.clear();

//titular
this->datosZumbido += sBodyBoundary + "Content-Disposition: form-data; name=\"data[Zumbido][titular]\"" + sENTER
this->datosZumbido += sENTER+ this->txtTitular->getText() + sENTER;

//cuerpo
this->datosZumbido += sBodyBoundary + "Content-Disposition: form-data; name=\"data[Zumbido][cuerpo]\"" + sENTER
this->datosZumbido += sENTER+ this->txtCuerpo->getText()+ sENTER;

//Imagen
this->datosZumbido += sBodyBoundary + "Content-Disposition: form-data; name=\"data[Upload][0][file]\"; filename=\"" + sImagen + "\"" + sENTER;
this->datosZumbido += "Content-Type: image/jpeg" + sENTER+ sENTER;

//get the global handle
int iSizeImg=maGetDataSize(this->ziudad->getFotoData());
char *rawData=new char[iSizeImg];
maReadData(this->ziudad->getFotoData(), rawData, 0, iSizeImg);

this->datosZumbido.append(rawData, iSizeImg);
this->datosZumbido+=sENTER;

//Fin de llamada
this->datosZumbido+=sBodyBoundaryEnd;

//Preparamos la transmisión
int iSize = this->datosZumbido.size();
String sContentType="multipart/form-data; boundary="+sHeaderBoundary;

this->httpConnZumbido->setRequestHeader("Content-Length", integerToString(iSize).c_str());
this->httpConnZumbido->setRequestHeader("Content-Type", sContentType.c_str());

//Iniciamos el envío de datos
this->httpConnZumbido->write(this->datosZumbido.c_str(), iSize);
}
}

Davide Mari
DavidSeas's picture
Offline
Mobile Conjurer
Joined: 10 May 2012
Posts:
Thank you very much

Thank you very much

Sam Pickard
rival's picture
Offline
Mobile Archmage
Joined: 19 Mar 2009
Posts:
http://www.mosync.com/content

http://www.mosync.com/content/string-handling-base64

Davide Mari
DavidSeas's picture
Offline
Mobile Conjurer
Joined: 10 May 2012
Posts:
Hi gerdodel   the

Hi gerdodel

 

the globalhandle is the data handler (obtained by placeholder) and that is filled by maCameraSnapshot function.

Concerning server and header I created a custom http server in C#  which read binary data and show the image so I cannot help you with PHP and i only set the charset header.

A question to Sam: How can I convert image in Base64 (maybe I will use in the future)

gerdodel
gerdodel's picture
Offline
Mobile Conjurer
Joined: 20 Mar 2012
Posts:
Hello Davide. I still can not

Hello Davide.

I still can not send the photo. Please, can you explain the whole process?

Where you define the globalhandle? In the resource file?

What you send in the POST headers?

How do you read the image in PHP?

Thanks.

Sam Pickard
rival's picture
Offline
Mobile Archmage
Joined: 19 Mar 2009
Posts:
OK, if you've got an MAHandle

OK, if you've got an MAHandle you can see on screen, then that is a decoded bitmap resource.  If it is a file on the device, a PNG or a JPEG, then it is an encoded, compressed file.  I'm guessing that you don't want to post the bitmap. As Davide has shown here, the is no problem whatsoever in posting data on an HTTP connection, but remember that your server may not be expecting binary data but Base64 instead.  You just need the handle to the data you want to send, you use HttpConnection::writeFromData() method.  Also, remember that this method is asyncronous, so the handle has to be kept until the connWriteFinished method is called. 

Davide Mari
DavidSeas's picture
Offline
Mobile Conjurer
Joined: 10 May 2012
Posts:
Hi all, I don't know if it is

Hi all,

I don't know if it is the absolutely correct solution, but I finally find a way to send the image. globalHandle is the handler returned by maCameraSnapshot

byte rawData[maGetDataSize(globalHandle)];

mLog->setText(Convert::toString(maGetDataSize(globalHandle)));

maReadData(globalHandle, rawData, 0, maGetDataSize(globalHandle));

maWriteData(globalHandle, rawData, 0, maGetDataSize(globalHandle));

mHttp.writeFromData(globalHandle,0, maGetDataSize(globalHandle));

Davide Mari
DavidSeas's picture
Offline
Mobile Conjurer
Joined: 10 May 2012
Posts:
Hi gerdodel Unfortunately

Hi gerdodel

Unfortunately it's the same for me. I found this other discussion  http://www.mosync.com/content/posting-http-server and maybe could be usefull. In particular maybe it's possible to save the image in the store and the read it and send

However I still think that it's necessary some type of conversion to send the image Handler

gerdodel
gerdodel's picture
Offline
Mobile Conjurer
Joined: 20 Mar 2012
Posts:
Hi Davide. I think I'm wrong

Hi Davide.

I think I'm wrong and the file is still not sent.

gerdodel
gerdodel's picture
Offline
Mobile Conjurer
Joined: 20 Mar 2012
Posts:
Hi Davide. You're right. No

Hi Davide.

You're right. No data is being sent.

As I read does not need to call 
httpConn->finish() so that the headers are sent.

But after putting httpConn->finish () the file appears to be sent. Can you check this in your process?

int iSizeImg=maGetDataSize(this->zumbido->getImagenDataHandle());

 

if (this->httpConnImagen->isOpen()) this->httpConnImagen->close();

this->httpConnImagen->create(sAux, HTTP_POST);

this->httpConnImagen->setRequestHeader("Content-Length", integerToString(iSizeImg).c_str());

this->httpConnImagen->setRequestHeader("Content-Disposition", "form-data; name=\"upload\"; filename=\"zumbidoMovil.jpg\"");

this->httpConnImagen->setRequestHeader("Content-Type", "image/jpeg");

this->httpConnImagen->setRequestHeader("Content-Transfer-Encoding", "binary");

//Fuerza el envio de las cabeceras

this->httpConnImagen->finish();

 

//Iniciamos el envío de datos

this->httpConnImagen->writeFromData(this->zumbido->getImagenDataHandle(), 0, iSizeImg);

 

Davide Mari
DavidSeas's picture
Offline
Mobile Conjurer
Joined: 10 May 2012
Posts:
Hi gerdodel I had already

Hi gerdodel

I had already tried using the writeFromData with the handle returned by maCameraSnapshot. But sniffing traffic with wireshark I saw that no packets are sent to the server. So I don't know if the handle must be some way modfiied.

gerdodel
gerdodel's picture
Offline
Mobile Conjurer
Joined: 20 Mar 2012
Posts:
Please, can you explain how

Please, can you explain how you send your file and how to receive it in PHP?

This is what I do to capture the image, what I do to send it to the server and what I do to read it there:

// To take the snapshot

 void TCamara::sacarFoto()

{

if(this->imagenDataH != 0) maDestroyPlaceholder(this->imagenDataH);

this->imagenDataH = maCreatePlaceholder();

maCameraSnapshot(this->formatoCamara, this->imagenDataH);

//set the handle of the picture

this->zumbido->setImageDataHandle(this->imagenDataH);

this->imagenDataH=0;

}

 

//To send the image

 void TNuevoZumbidoDatos::enviarImagen()

{

if (this->httpConnImagen->isOpen()) this->httpConnImagen->close();

if (this->httpConnImagen->create(this->urlPhpServer, HTTP_POST)<0) msjError("Error");

//get the handle of the picture

 MAHandle h=this->zumbido->getImageDataHandle();

int iSizeImg=maGetDataSize(h);

this->httpConnImagen->setRequestHeader("Content-Length", integerToString(iSizeImg).c_str());

this->httpConnImagen->setRequestHeader("Content-Type", "multipart/form-data; filename=\"zumbidoMovil.jpg\"");

this->httpConnImagen->writeFromData(h, 0, iSizeImg);

}

 

//communication seems to work, but the PHP server get no file:

 function movilAppCrearImagenZumbido()

{

        $this->traza("_POST=". serialize($_POST));

        if ($_FILES["file"]["error"] > 0)

        {

            $this->traza("Error: " . $_FILES["file"]["error"]);

        }

        else

        {

            $this->traza("name: " . $_FILES["file"]["name"]);

            $this->traza("Type: " . $_FILES["file"]["type"]);

            $this->traza("size: " . $_FILES["file"]["size"]);

            $this->traza("Stored in: " . $_FILES["file"]["tmp_name"]);

        }

}

//The traza:

10:04:06: _POST=a:0:{}

10:04:06: name: 

10:04:06: Type: 

10:04:06: size: 

10:04:06: Stored in: 

 

 

gerdodel
gerdodel's picture
Offline
Mobile Conjurer
Joined: 20 Mar 2012
Posts:
I'm solving the same

I'm solving the same problemIf I succeed I will tell you how I did. 

Please, if you get it before me, post the solution here.

Davide Mari
DavidSeas's picture
Offline
Mobile Conjurer
Joined: 10 May 2012
Posts:
Can anyone help me?

Can anyone help me?

Davide Mari
DavidSeas's picture
Offline
Mobile Conjurer
Joined: 10 May 2012
Posts:
Hi all, hoping it could be

Hi all,

hoping it could be usefull I have foud hoe to correctly insert the resource as binary:

.res SENDIMAGE

.bin 

.include "splash_nologo.png"

However I'm already looking for a way to convert the image handler obtained by camerasnapshot to a binary that I can send via http

Davide Mari
DavidSeas's picture
Offline
Mobile Conjurer
Joined: 10 May 2012
Posts:
Hi Sam Thank you for your

Hi Sam

Thank you for your fast response. I tried to insert it as you said but I get a compile error:

In File 'C:\MoSync\workspace\Scontrino3\Resources\Resources.lst': Error: Illegal resource directive '', 

Pipe tool failed. (See console for more information).

 Command line: c:\MoSync\bin\pipe-tool.exe -appcode=YYVK -R -depend=C:\MoSync\workspace\Scontrino3\Output\Release\Android\2.x\resources.deps C:\MoSync\workspace\Scontrino3\Output\Release\Android\2.x\resources C:\MoSync\workspace\Scontrino3\Resources\Resources.lst

This is my resource file:

.res SPLASH_NOLOGO

.image "splash_nologo.png"

 

.res SENDIMAGE

.bin "splash_nologo.png"

 

.res SCRITTA_FINALE

.image "scritta_finale_invisibile.png"

 

.res LOGO

.image "logo_beta_invisible.png"

 

.res RES_TAB_ICON_COLORS

.image "Icons/TabIconColors.png"

 

.res RES_TAB_ICON_COLORS_ANDROID

.image "Icons/TabIconColors_Android.png"

 

.res RES_TAB_ICON_WEB_VIEW

.image "Icons/TabIconWebView.png"

 

.res RES_TAB_ICON_WEB_VIEW_ANDROID

.image "Icons/TabIconWebView_Android.png"

 

.res RES_TAB_PROFILE_ANDROID

.image "Icons/tabProfileAndroid.png"

 

.res RES_TAB_CAMERA_ANDROID

.image "Icons/tabCameraAndroid.png"

 

.res RES_TAB_CHRONO_ANDROID

.image "Icons/tabChronoAndroid.png"

 

.res RES_TAB_PROMO_ANDROID

.image "Icons/tabPromoAndroid.png"

 

.res RES_TAB_HELP_ANDROID

.image "Icons/tabHelpAndroid.png"

 

After that I have another problem. Assuming that I can send a single image inserted in the resource file, I get the same error when I try to send image obtained after a snapshot (essentially the ImageScreen described in CameraDemo). How can I solve it?

Thanks

Sam Pickard
rival's picture
Offline
Mobile Archmage
Joined: 19 Mar 2009
Posts:
Hi Davide, SPLASH_NOLOGO

Hi Davide, SPLASH_NOLOGO won't be a data object, but a decoded image resource.  It will have been converted from the PNG encoded file to a displayable bitmap.

In the resource file, you can include it to send like this

{syntaxhighlighter brush: cpp;fontsize: 100; first-line: 1; }.res SENDIMAGE
.bin "Images/splash_nologo.png"{/syntaxhighlighter}

Login or register to post comments