Viewed   247 times

I've been looking for a solution to this for hours, but I can't find any.

Basically, I want to upload, from my android device, files to an http website. However, I have no clue whatsoever how to do this. I'm using java on the device, and I would like to use PHP on the server-side of things. I just want to upload the files, not do anything fancy with them on the server.

Can anyone provide code and/or a good link to what I need? I have little to no experience in this, and I am at a loss.

Thanks, NS

PS. I have no experience in PHP coding.

 Answers

4

Yeah, so I found the java-side of things. This works, so... yeah.

public class Uploader extends Activity {

    private String Tag = "UPLOADER";
    private String urlString = "YOUR_ONLINE_PHP";
    HttpURLConnection conn;

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

        String exsistingFileName = "/sdcard/uploader/data/testfile";

        String lineEnd = "rn";
        String twoHyphens = "--";
        String boundary = "*****";
        try {
            // ------------------ CLIENT REQUEST

            Log.e(Tag, "Inside second Method");

            FileInputStream fileInputStream = new FileInputStream(new File(
                    exsistingFileName));

            // open a URL connection to the Servlet

            URL url = new URL(urlString);

            // Open a HTTP connection to the URL

            conn = (HttpURLConnection) url.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: post-data; name=uploadedfile;filename="
                            + exsistingFileName + "" + lineEnd);
            dos.writeBytes(lineEnd);

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

            // create a buffer of maximum size

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

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

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

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

            // 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();
            dos.close();

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

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

        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                    .getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                Log.e("Dialoge Box", "Message: " + line);
            }
            rd.close();

        } catch (IOException ioex) {
            Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
        }
    }
}
Saturday, September 17, 2022
2

Server-side validation is a must, client-side validation is a plus.

If you only use client-side validation, nefarious people will hack your system to post un-validated stuff - breaking your scripts, and potentially exploiting your system. This is very bad from a security standpoint.

That said, you should also include client-side validation, since that's much quicker than a round trip to the server, and gives your users instant feedback. This'll keep your users happy, and will have them coming back to your site.

So, if possible, use both. If you can't/won't, then at least do it server-side. Client-side-only validation is a recipe for disaster!

Thursday, October 20, 2022
1

Just add a a few FormBodyPart to your MultipartEntity.

You can use the StringBody object to provide the value.

Here is an example of how you can use it:

byte[] data = {10,10,10,10,10}; 
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("server url");
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", bab);

FormBodyPart bodyPart=new FormBodyPart("formVariableName", new StringBody("formValiableValue"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName2", new StringBody("formValiableValue2"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName3", new StringBody("formValiableValue3"));
reqEntity.addPart(bodyPart); 
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while((line = in.readLine()) != null) {
    System.out.println(line);
}

Here is the output of the PHP script:

$_FILES
Array
(
    [image] => Array
        (
            [name] => image.jpg
            [type] => application/octet-stream
            [tmp_name] => /tmp/php6UHywL
            [error] => 0
            [size] => 5
        )

)
$_POST:
Array
(
    [formVariableName] => formValiableValue
    [formVariableName2] => formValiableValue2
    [formVariableName3] => formValiableValue3
)

This doesn't compress all the post vars inside of one content body part but it dose the job.

You can't access the data from php://stdin or $HTTP_RAW_POST_DATA, both are unavailable for multipart/form-data encoding. From the PHP docs:

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

Even if you set always_populate_raw_post_data to On it still won't fix the problem:

Always populate the $HTTP_RAW_POST_DATA containing the raw POST data. Otherwise, the variable is populated only with unrecognized MIME type of the data. However, the preferred method for accessing the raw POST data is php://input. $HTTP_RAW_POST_DATA is not available with enctype="multipart/form-data".

My best guess is just add all the data as a ByteArrayBody or StringBody and just use that as if you were reading from php://stdin

Here is an example of ByteArrayBody:

String testString="b=a&c=a&d=a&Send=Send";
reqEntity.addPart(new FormBodyPart("formVariables", new ByteArrayBody(testString.getBytes(), "application/x-www-form-urlencoded", "formVariables")));

And in PHP:

var_dump(file_get_contents($_FILES['formVariables']['tmp_name']));

You should get:

string(21) "b=a&c=a&d=a&Send=Send"

Edit: After some second thoughts I think it's better to just use one StringBody and put all the data in one post variable, then parse it from that, it skips writing the data to a file and deleting it after the request since the temp file is totally useless this will increase performance. Here is an example:

String testString="b=a&c=a&d=a&Send=Send";
bodyPart=new FormBodyPart("rawData", new StringBody(testString));
reqEntity.addPart(bodyPart);

Then from PHP:

var_dump($_POST['rawData']);
Wednesday, October 19, 2022
 
bug0r
 
4
  1. Download a file.

You are on the right track here, but the reason why result.body is always empty is because your file service is returning a 302 redirection rather than the file itself. You need to follow this redirection. Here is a simple implementation, specific to your use case only, which works:

  var url: String = "http://dropcanvas.com/ir4ok/1"
  var result: Response!
  while true {
    result = try drop.client.get(url)
    guard result.status == .found else { break }
    url = result.headers["Location"]!
  }
  let body = result.body
  1. Send a file.

The very best method is to save your file in your Vapor app's Public directory, and either have your client request the public URL directly, or return a 302 response of your own pointing to it.

If you expressly want to hide the permanent home of the file or e.g. perform authentication then you can return the file from your own route using Vapor's own FileMiddleware as a guide.

Sunday, August 21, 2022
 
goozo
 
4

try this

class getEditingHUD extends AsyncTask<String, Long, Integer> {

    protected void onPreExecute() {
        super.onPreExecute();
        loading = ProgressDialog.show(HtmlViwer.this, null,
                "Please wait...");
    }

    protected Integer doInBackground(String... params) {
        File file = new File(Environment.getExternalStorageDirectory(), "yourfile.html");
        try {
            FileInputStream fis = new FileInputStream(file);
            String myserver = "http://your server/phpfile.php";
            HttpFileUploader htfu = new HttpFileUploader(myserver,
                    "noparamshere", Modules.currentProgram + ".html");
            htfu.doStart(fis);
        } catch (Exception e) {
            Log.e("Error Readingfile", e.toString());
        }

        return null;
    }

    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        try {
            if (loading != null && loading.isShowing())
                loading.dismiss();
        } catch (Throwable t) {

        }
    }

}

and this HttpFileUploader class

public class HttpFileUploader implements Runnable {

URL connectURL;
String params;
String responseString;
// InterfaceHttpUtil ifPostBack;
String fileName;
byte[] dataToServer;

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;
    PrakitoServer();
}

FileInputStream fileInputStream = null;

void PrakitoServer() {
    String exsistingFileName = "print.html";

    String lineEnd = "rn";
    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=""
                        + exsistingFileName + """ + 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: " + ex.getMessage(), ex);
    }

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

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

}

}

Tuesday, November 1, 2022
 
tomo
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :