2

I want user to upload pdf to server and make it downloadable to other user.I want to save the url of uploaded file to databse and then pickup that url to display the other user. I am learning android , so i dont have much idea . here is my code , i had tried to do it using multipart:-

public class Upload extends Activity {
String path=null;
private String getpath(String path){
    return path;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
Button browse = (Button) findViewById(R.id.browse);
Button upload = (Button) findViewById(R.id.upload);
browse.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        Intent intent = new Intent();
        intent.setType("application/pdf");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select PDF"), 1);


    }

});

upload.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        upload up = new upload(); 
        up.execute();

    }
});

}
 public void onActivityResult(int requestCode, int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
    if (requestCode == 1) {
        Uri data = result.getData();
         String pathe = data.getPath();
         path = getpath(pathe);
         Toast.makeText(Upload.this, path, Toast.LENGTH_SHORT).show();
}
}
}




private class upload extends AsyncTask<Void, Void, Void>{
ProgressDialog pd;
@Override
protected void onPreExecute() {
pd= ProgressDialog.show(Upload.this, "Uploading", "Please Wait");
super.onPreExecute();
}
@Override
    protected void onPostExecute(Void result) {
    pd.dismiss();
    super.onPostExecute(result);
    }
@Override
protected Void doInBackground(Void... params) {
    //Toast.makeText(Upload.this, path,Toast.LENGTH_LONG).show();

    String url = "http://192.168.43.50/projectpri/upload.php";
    File file = new File(path);
    file.getAbsolutePath();
    try {
        HttpClient httpclient = new DefaultHttpClient();   
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(url);
        MultipartEntity mpe = new MultipartEntity();
        ContentBody cbfile =new FileBody(file);
        mpe.addPart("file", cbfile);
        httppost.setEntity(mpe);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity ent = response.getEntity();
        System.out.println(response.getStatusLine());

    } catch (Exception e) {
        // show error
    }
    return null;
}

}

Mayank Khursija
  • 83
  • 1
  • 1
  • 8

2 Answers2

4

Full working example, tested for files over 100 Mb, replace your_package with your package name.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your_package" >

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Layout activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Browse"
        android:id="@+id/browse"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload"
        android:id="@+id/upload"/>
</LinearLayout>

Activity MainActivity

package your_package;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    Uri path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button browse = (Button) findViewById(R.id.browse);
        Button upload = (Button) findViewById(R.id.upload);

        browse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.setType("application/pdf");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select PDF"), 1);
            }
        });
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                (new Upload(MainActivity.this, path)).execute();

            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                path = result.getData();
            }
        }
    }
}

class Upload extends AsyncTask<Void, Void, Void> {
    private ProgressDialog pd;
    private Context c;
    private Uri path;

    public Upload(Context c, Uri path) {
        this.c = c;
        this.path = path;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = ProgressDialog.show(c, "Uploading", "Please Wait");
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        pd.dismiss();
    }

    @Override
    protected Void doInBackground(Void... params) {
        String url_path = "http://192.168.43.50/projectpri/upload.php";
        HttpURLConnection conn = null;

        int maxBufferSize = 1024;
        try {
            URL url = new URL(url_path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setChunkedStreamingMode(1024);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data");

            OutputStream outputStream = conn.getOutputStream();
            InputStream inputStream = c.getContentResolver().openInputStream(path);

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

            int bytesRead;
            while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            inputStream.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                Log.i("result", line);
            }
            reader.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }
}

Server side PHP

$file_name = date("U").".pdf"; //name of your file
$server_path = "/path/to/file/folder/"; //server path to folder
$web_path = "http://192.168.43.50/projectpri/file/"; //web path to folder

$file = $server_path.$file_name;
file_put_contents($file,"");

$fp = fopen("php://input", 'r');
while ($buffer =  fread($fp, 8192)) {
    file_put_contents($file,$buffer,FILE_APPEND | LOCK_EX);
}

echo $web_path.$file_name;
Sam Ivichuk
  • 999
  • 1
  • 10
  • 22
1

First thing is that you shouldn't use HttpClient, MultipartEntitiy because they are deprecated and not used at all and not recommended by http://developer.android.com/.

  • I have also used your these classes, but it's time to upgrade to the market and updates with the current android M.
  • I also know that maximum tutorials on internet are related to HttpClient etc. which are not useful for current time go for HttpUrlConnection.

For you convenience check the following links:

General knowledge:

Android deprecated apache module (HttpClient, HttpResponse, etc.)

http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html

For post to server helpful links for you:

http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically

Upload multiple image file using HttpURLConnection

http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically

For posting data to server you can also use library with less effort like volley, Retrofit. etc.

You have to do some experiment on it which will safe future of your code around various android versions and in effective manner.

Thanks

Community
  • 1
  • 1
Androider
  • 3,833
  • 2
  • 14
  • 24