Hi all,

I'm currently working on an application which need to upload a jpg or
png file to my webserver.

I've tried many solutions from example picked on websites tutorials.
Every time I've got an error in the HTTP response with error code = 0.

The code I've tried is below.

Do you have any suggestion or resolution please ?
Thank you for your attention.

Floopi

PHP Code on my server is fileUpload.php:
----------------------------------------

<?php

// Where the file is going to be placed
$target_path =  $_SERVER['DOCUMENT_ROOT']."/uploads";

//Add the original filename to our target path.
$file = basename($_FILES['uploadedfile']['name']);

echo "target_path= ".$target_path." ";

//pour tester que c'est bien une image
$extensions = array('.png', '.gif', '.jpg', '.jpeg', '.JPG', '.JPEG');
$extension = strrchr($_FILES['uploadedfile']['name'], '.');

//check if the file is uploaded
if(in_array($extension, $extensions)) {

  if(is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) {
    echo "Fichier= ". $_FILES['uploadedfile']['name'] ."
telechargement OK.\n";

    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],
$target_path) === TRUE) {
      echo "The file ".  basename( $_FILES['uploadedfile']['name']).
        " has been uploaded";
    } else {
      echo "There was an error uploading the file, please try again!";
      echo "error =".basename($_FILES['uploadedfile']['error']);
      echo "file=".$_FILES['uploadedfile']['tmp_name'];
    }

  } else {
    echo " Nom du fichier : '". $_FILES['uploadedfile']['name'];
  }
 } else {
  echo "mauvaise extension de fichier";
 }

?>
-----------------------------------------------------------------------------------------------------------------------------------------------------

Android code :
---------------------
First, the main class :
-------------------------------

package com.floopi.testUpload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class testUpload extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);

                //validation nom / commentaires
                final Button okbutton = (Button) findViewById(R.id.upload);
                okbutton.setOnClickListener(upload_listener);
        }

        OnClickListener upload_listener = new OnClickListener() {
                public void onClick(View v) {
                        // Perform Actions on clicks : start activity AddPticoin
                        uploadFile();
                }
        };

        public void uploadFile(){
                String urlString = 
"http://www.mysite.com/script/fileUpload.php";;
                String name = "2CVjaune.jpg";

                try {
                        FileInputStream fis =this.openFileInput(name);
                        HttpFileUploader htfu = new HttpFileUploader
(urlString,"noparamshere", "2CVjaune.jpg");
                        htfu.doStart(fis);
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
}


Next, the class HttpFileUploader :
-----------------------------------------------

package com.floopi.testUpload;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;

public class HttpFileUploader implements Runnable{

        URL connectURL;
        String params;
        String responseString;
        String fileName;
        byte[ ] dataToServer;
        FileInputStream fileInputStream = null;

        HttpFileUploader(String urlString, String params, String fileName ){
                try{
                        connectURL = new URL(urlString);
                }catch(Exception ex){
                        Log.i("URL FORMATION","MALFORMATED URL");
                }
                this.params = params+"=";
                this.fileName = fileName;

        }


        void doStart(FileInputStream stream){
                fileInputStream = stream;
                thirdTry();
        }

        void thirdTry(){
                String existingFileName = "2CVjaune.jpg";

                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                String Tag="3rd";
                try
                {
                        //------------------ CLIENT REQUEST

                        Log.e(Tag,"Starting to bad things");
                        // Open a HTTP connection to the URL

                        HttpURLConnection conn = (HttpURLConnection)
connectURL.openConnection();

                        // Allow Inputs
                        conn.setDoInput(true);

                        // Allow Outputs
                        conn.setDoOutput(true);

                        // Don't use a cached copy.
                        conn.setUseCaches(false);

                        // Use a post method.
                        conn.setRequestMethod("POST");

                        conn.setRequestProperty("Connection", "Keep-Alive");

                        conn.setRequestProperty("Content-Type", "multipart/form-
data;boundary="+boundary);

                        DataOutputStream dos = new DataOutputStream( 
conn.getOutputStream
() );

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; 
name=\"uploadedfile
\";filename=\"" + existingFileName +"\"" + lineEnd);
                        dos.writeBytes(lineEnd);

                        Log.e(Tag,"Headers are written");

                        // create a buffer of maximum size

                        int bytesAvailable = fileInputStream.available();
                        int maxBufferSize = 1024;
                        int bufferSize = Math.min(bytesAvailable, 
maxBufferSize);
                        byte[ ] buffer = new byte[bufferSize];

                        // read file and write it into form...

                        int bytesRead = fileInputStream.read(buffer, 0, 
bufferSize);

                        while (bytesRead > 0)
                        {
                                dos.write(buffer, 0, bufferSize);
                                bytesAvailable = fileInputStream.available();
                                bufferSize = Math.min(bytesAvailable, 
maxBufferSize);
                                bytesRead = fileInputStream.read(buffer, 0, 
bufferSize);
                        }

                        // send multipart form data necesssary after file 
data...

                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + 
lineEnd);

                        // close streams
                        Log.e(Tag,"File is written");
                        fileInputStream.close();
                        dos.flush();

                        InputStream is = conn.getInputStream();
                        // retrieve the response from server
                        int ch;

                        StringBuffer b =new StringBuffer();
                        while( ( ch = is.read() ) != -1 ){
                                b.append( (char)ch );
                        }
                        String s=b.toString();
                        Log.i("Response",s);
                        dos.close();


                }
                catch (MalformedURLException ex)
                {
                        Log.e(Tag, "error URL: " + ex.getMessage(), ex);
                }

                catch (IOException ioe)
                {
                        Log.e(Tag, "error IO: " + ioe.getMessage(), ioe);
                }
        }


        @Override
        public void run() {
                // TODO Auto-generated method stub

        }

}

-- 
You received this message because you are subscribed to the Google
Groups "Android Beginners" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-beginners?hl=en

Reply via email to