Search code examples
phpandroidpdfuploadmultipart

Upload pdf file to server and get its url


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;
}

}


Solution

  • 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;