0

I'm not an expert on PHP so I'have taken many things from the Internet and from questions of this page. I need to send a file to a WAMP server (sing s PHP Script) plus sending a String in order to create the target path, which will depend on the date plus the sent string. At the moment the target path is based only on the actual date. For example 2013-09-27, but I would like to be 2013-09-27-XX where XX is the string sent by the device to the server alongside the uploaded file.

Here is the code which I use to upload the file to the server.

 public void upload() throws Exception {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String pathToOurFile = "/sdcard/"+Ident.getDNI()+"_"+Nombres.getNom()+"_"+Nombres.getApe1()+"_"+Nombres.getApe2()+".xml";
        String urlServer = "http://10.0.0.15/subida/upload_file.php";

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

            FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
            URL url = new URL(urlServer);

            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream
                    .writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                            + pathToOurFile + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

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

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

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

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

            String serverResponseMessage = connection.getResponseMessage();


            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
    }

Here is the PHP Script I use to get the file (based on date):

<?php
mkdir($target_path.date("Y-m-d"));
$target_path = $target_path  .date("Y-m-d") ."/" .basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
 echo "El fichero ".  basename( $_FILES['uploadedfile']['name'])." ha sido enviado";
} else{
 echo "Hubo un error, inténtalo de nuevo!";
}
?>

I assume I should add here something like $SentString = $_POST('sentstring) and then add it to the target path:

 $target_path = $target_path  .date("Y-m-d")-$SentString ."/" .basename( $_FILES['uploadedfile']['name']);

But what should I add to the Android client part?

Thank you for your time

1 Answer 1

1

While looking at your code this is multipart request and you can use multipart libraries to upload multipart files.

download below libraries

apache-mime4j-0.6.jar
httpclient-4.1.jar
httpcore-4.1.jar
httpmime-4.1.jar

and below few lines of code to upload the code

try {
                HttpClient httpClient = new DefaultHttpClient();
                httpClient.getParams().setParameter(
                        CoreProtocolPNames.PROTOCOL_VERSION,
                        HttpVersion.HTTP_1_1);
                HttpPost post   = new HttpPost(url);

                post.setHeader("Content-Type", "image/jpg");

                MultipartEntity entity = new MultipartEntity();
                entity.addPart("image",  new FileBody(new File(filePath)));
                post.setEntity(entity);
                try {
                    HttpResponse response = httpClient.execute(post);
                    System.out.println("response -- " + response.getEntity().getContent());

                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }

use below string to add string data

entity.addPart("date", new StringBody("date"));
Sign up to request clarification or add additional context in comments.

2 Comments

Hi thank you for the help, but is there a way of still using the code I use at the moment?
Actually this libraries are easy to use from client side and the data will be easy to parse from server side too. as you can see in the entity we can send string value pairs too. so according to me. it will not take more than 5 min to replace this code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.