1

This is my code.But my server don't get the correct data I am trying to send a file via httpclient I also read that http client is deprecated after 6.0 so what method should i use instead and can any post their working/running code where I can send my word/pdf/text files via my android phone to a php server

package com.example.sendfiletoserver;

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;


public class SendFileToServer extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_file_to_server);
        new postFileAsync().execute();
    }

    private void uploadFile() throws ClientProtocolException, IOException {
        String file=Environment.getExternalStorageDirectory().getAbsolutePath()+"/Test.pdf";
        Log.d("Mayur", ""+file);

        HttpClient httpclient=new DefaultHttpClient();
        HttpPost post=new HttpPost("<My_address>");         //My server address
        File f=new File(file);
        FileBody filebody=new FileBody(f);
        MultipartEntity mentity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mentity.addPart("file", filebody);
        post.setEntity(mentity);
        HttpResponse responce=httpclient.execute(post);
        HttpEntity entity=responce.getEntity();

    }

    public class postFileAsync extends AsyncTask<Void, Void, Void> {
//      ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
//          pd = new ProgressDialog(SendFileToServer.this);
//          pd.setCancelable(false);
//          pd.setMessage("Uploading File");
//          pd.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            try {
                uploadFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
//          pd.dismiss();
        }

    }
}

This is my php code

<?php
// if text data was posted
if ($_POST) {
    print_r($_POST);
}

// if a file was posted
else if ($_FILES) {
    $file         = $_FILES['file'];
    $fileContents = file_get_contents($file["tmp_name"]);
    print_r($fileContents);
}
?>

I don’t have any idea about php so if any could give me the php code to help me. I don’t even know weather my code id right or not

thank u in advance

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
  • take a look : http://stackoverflow.com/questions/4126625/how-to-send-a-file-in-android-from-mobile-to-server-using-http – Ozan Oct 20 '15 at 07:40

1 Answers1

0

you can use this, this code is working for me,

HttpURLConnection connection = null;
            HttpURLConnection.setFollowRedirects(false);
    connection.setRequestMethod("POST");
                    String boundary = "---------------------------boundary";
                    String tail = "\r\n--" + boundary + "--\r\n";
                    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                    connection.setDoOutput(true);
                    connection.setRequestProperty("Connection", "Keep-Alive");
                    connection.setRequestProperty("ENCTYPE", "multipart/form-data");

                    String metadataPart = "--" + boundary + "\r\n"
                            + "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
                            + "" + "\r\n";

                    String fileHeader1 = "--" + boundary + "\r\n"
                            + "Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""
                            + URLEncoder.encode(fileName, "UTF-8") + "\"\r\n";
    //                        + "Content-Type: application/octet-stream\r\n"
    //                        + "Content-Transfer-Encoding: binary\r\n";

                    long fileLength = file.length() + tail.length();
                    String fileHeader2 = "Content-length: " + fileLength + "\r\n";
                    String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
                    String stringData = metadataPart + fileHeader;
                    long requestLength = stringData.length() + fileLength;
                    connection.setRequestProperty("Content-length", "" + requestLength);
                    connection.setRequestProperty("Connection", "close");
                    connection.setFixedLengthStreamingMode((int) requestLength);
                    connection.connect();
                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                    out.writeBytes(stringData);
                    out.flush();
                    int progress = 0;
                    int bytesRead = 0;
                    int totbyts = 0;
                    byte buf[] = new byte[1024];
                    BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
                    while ((bytesRead = bufInput.read(buf)) > 0) {
                        // write output
                        out.write(buf, 0, bytesRead);
                        out.flush();
                        totbyts += bytesRead;
                        // update progress bar
                        progress = (int) (totbyts * 100 / file.length());
                        publishProgress(progress);
                        if (isCancelled()) {
                            connection.disconnect();
                            break;
                        }
                    }

and your php code is also working. Hope this workd for you. i know it is quite late answer

Parth Anjaria
  • 3,961
  • 3
  • 30
  • 62
  • Yes it is late,I accept the answer because i did it by the same way.This method is good as HttpClient is deprecated in API 23.Here 'connection' is the object of HttpUrlConnection .Thank you @Parth –  Jan 07 '16 at 11:20