Saving an image from device on remote server

  • Replies:19
  • Answered
Itzick Binder
  • Forum posts: 21

Nov 13, 2014, 12:51:30 AM via Website

Hi everybody. I'm trying to create an android application that on one of its activities the user can save an image on a remote server. On my server I have a folder name ibuy. Inside it I have a folder name files with a php file that suppose to handle the saving of the images on the server. Inside it I have another folder name files.
This is my php file:

<?php

    $file_path = "ibuy.pixub.com/ibuy/files/";

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
?>

(The parameter $file_path begins with "h t t p: //")

This is the code inside the activity that is activated after the button is pressed:

final File file = new File(path);
        new Thread(new Runnable() {
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {
                    }
                });
                uploadFile();
            }
        }).start();

The property "path" is a correct path to an image on the device.
This is the uploadFile function:

public int uploadFile() {
    final String upLoadServerUri = "ibuy.pixub.com/ibuy/files/UploadToServer.php";
    HttpURLConnection conn;
    DataOutputStream dos;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(path);
    int serverResponseCode = 0;

    if (!sourceFile.isFile()) {
        Log.e("uploadFile", "Source File not exist : " + path);

        return 0;
    } else {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", path);

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

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

            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available();

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

            // read file and write it into form...
            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);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

            if (serverResponseCode == 200) {

                runOnUiThread(new Runnable() {
                    public void run() {
                        Log.i("uploadFile", "Path is : " + path);
                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            ex.printStackTrace();

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            e.printStackTrace();

            Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
        }
        return serverResponseCode;

    }
}

(The parameter upLoadServerUri begins with "h t t p: //")

I copied almost everything from another user guide. It seems that the code works, I get the correct results. Can anybody give me a hand here, maybe tell me where I had a mistake? Thank you in advance!

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 13, 2014, 8:42:10 AM via App

Youre saying that you get the correct results plus that the code works. So what's it that you need because I really dont know :D

Reply
Itzick Binder
  • Forum posts: 21

Nov 13, 2014, 1:17:50 PM via Website

Everything is working fine but I can't see the images on the server, as if they didn't got there.

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 13, 2014, 1:52:41 PM via Website

Itzick Binder

Everything is working fine but I can't see the images on the server, as if they didn't got there.

Could you put the following code on the top of your code:

echo "<pre>";
var_dump($_FILES);
echo "</pre>";

Please copy and paste the outcome of that in a reply :)

Reply
Itzick Binder
  • Forum posts: 21

Nov 13, 2014, 6:07:07 PM via Website

I copied the code and placed it straight under the On the android studio log I see nothing and if I insert "ibuy.pixub.com/ibuy/files/UploadToServer.php" straight into the browser I receive this:
array(0) {
}
fail

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 13, 2014, 6:52:16 PM via App

Oh forgot to mention you have to read the content of the webpage through an inputstream in order to get the outcome. If you paste the url in the browser, it wont work ofcourse :P

Reply
Itzick Binder
  • Forum posts: 21

Nov 13, 2014, 7:04:08 PM via Website

How do I do that? What to change in my php file or my java file?

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 13, 2014, 7:14:08 PM via App

I cant really be bothered for tonight but I will explain it in short. If you'd still have issues by tomorrow afternoon, I will give you my sample code for that.

This should be done in Java. After you get a response code from your httpconnection, you need to receive the printed php content from the document. Simple search for: Receive html content after fileoutputstream android.

That should get you on the correct path of finding the code that you need for it. Currently on my android phone so I cant write down the code for you with full explanation :)

Reply
Itzick Binder
  • Forum posts: 21

Nov 14, 2014, 12:43:12 PM via Website

I tried looking for answers as you suggested and found nothing. Can you please post your sample code? Thanks

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 14, 2014, 1:56:41 PM via Website

Replace the following:

if (serverResponseCode == 200) {

    runOnUiThread(new Runnable() {
        public void run() {
            Log.i("uploadFile", "Path is : " + path);
        }
     });
}

With the following:

if (serverResponseCode == 200) {
    // Read response
    StringBuilder responseSB = new StringBuilder();
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String line;
    while ( (line = br.readLine()) != null)
         responseSB.append(line);

    // Close streams
    br.close();

    runOnUiThread(new Runnable() {
        public void run() {
            Log.i("uploadFile", "Path is : " + path);
            Log.i("Output", responseSB.toString());
        }
     });
}

I had something similar in my previous project but used it for JSON output instead. Can't wait for your reply with the outcome :)

Reply
Itzick Binder
  • Forum posts: 21

Nov 14, 2014, 3:10:18 PM via Website

I copied your code and this is the result i got:

The site won't let me upload the text because it contains links so I got a screen shot of it:image

I have absolutely no idea what to do now :(

Thank you for all your help!

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 14, 2014, 3:42:01 PM via Website

That output is really great thanks :) You can replace your previous code again to improve the app's performance in my previous reply.

The output told me that there's no $_FILES["uploaded_file"]. I figured that out by comparing the other dude's code with your's. After you replaced your previous code, do the following:

Search and select this:

name=" + path + ";

Replace it with this:

name=\"uploaded_file\";

Then it should work buddy ;)

Reply
Itzick Binder
  • Forum posts: 21

Nov 14, 2014, 3:58:04 PM via Website

I changed the java code from:

dos.writeBytes("Content-Disposition: form-data; name=" + path + ";filename=\"" + path + "\"" + lineEnd);

to:

dos.writeBytes("Content-Disposition: form-data; name=\\\"uploaded_file\\\";filename=\"" + path + "\"" + lineEnd);

and still it doesn't work.
Now the message I get is this:

User uploaded photo

Do you have any other suggestion? Thanks

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 14, 2014, 5:23:27 PM via App

You added too many \

Make sure you add the correct amount of slashes.

dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + path + "\"" + lineEnd);

This would be correct.

— modified on Nov 14, 2014, 5:37:53 PM

Reply
Itzick Binder
  • Forum posts: 21

Nov 14, 2014, 5:42:40 PM via Website

Still nothing
I changed it to:

dos.writeBytes("Content-Disposition: form-data; name=\\uploaded_file\\;filename=\"" + path + "\"" + lineEnd);

and it still didn't save the image.
The result is:
User uploaded photo

I'm beginning to become desperate :(

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 14, 2014, 5:51:10 PM via Website

Itzick Binder

Still nothing
I changed it to:

dos.writeBytes("Content-Disposition: form-data; name=\\uploaded_file\\;filename=\"" + path + "\"" + lineEnd);

and it still didn't save the image.
The result is:
User uploaded photo

I'm beginning to become desperate :(

Once again, you didn't exactly copy what I gave you :P

dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + path + "\"" + lineEnd);

Should do the trick.

Reply
Itzick Binder
  • Forum posts: 21

Nov 14, 2014, 6:13:45 PM via Website

I copied your code and still nothing.

This is the message I get now:

User uploaded photo

Maybe I should replace the "path" in

dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + path + "\"" + lineEnd);

with the "uploaded_file"?

What do you think?

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 14, 2014, 6:41:08 PM via Website

Itzick Binder

I copied your code and still nothing.

This is the message I get now:

User uploaded photo

Maybe I should replace the "path" in

dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + path + "\"" + lineEnd);

with the "uploaded_file"?

What do you think?

It's not a Java issue anymore. It's a PHP issue now. Your file path in php is not absolute and could cause the error that you're having.

Third line of your PHP script:

$file_path = "ibuy.pixub.com/ibuy/files/";

Change it to:

$file_path = "../files/";

— modified on Nov 14, 2014, 6:41:39 PM

Reply
Itzick Binder
  • Forum posts: 21

Nov 14, 2014, 6:51:41 PM via Website

It works! Thanks man. You Rock!!!!

Reply
Kevin Berendsen
  • Forum posts: 118

Nov 14, 2014, 7:53:55 PM via Website

Itzick Binder

It works! Thanks man. You Rock!!!!

Nice :) !

By the way, don't forget to mark the topic as answered. Go to your first post in this topic, go to the right top corner of the post, click on More and click on Set as Answered. Would help others as well with the same issue ;)

Reply