How to upload BD backup to the server using Okhttp?

Asked

Viewed 36 times

0

How to upload the . db file (Sqlite backup), from the android device to a server using the Okhttp, java and PHP library?

1 answer

1


Sussa!

In the Okhttp Recipes documentation there are some common demos. More specifically, you will have to use class properties MultipartBody.Builder() for sending the file.

In the square/okhttp has exactly what you want (PostFile.java), but for what you need, I made some basic changes. I’ll show you:

JAVA

Mypostfile.java

This is the class that makes everything happen, using Okhttpclient.

public final class MyPostFile{

    private final OkHttpClient client = new OkHttpClient();

    public void run() throws Exception {

        File file = new File(getExternalStorageDirectory().getAbsolutePath() + "/bkp_sqlite.db");

        if (file.length() != 0) {

            MultipartBody.Builder requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(),
                            RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), file));

            MultipartBody multBody = requestBody.build();    
            Request request = new Request.Builder()
                    .url("http://api.meusite.com/file")
                    .post(multBody)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                Log.wtf(PostFile.class.getSimpleName(), response.body().string());
            }
        }
    }    
    public static void main(String... args) throws Exception {
        new PostFile().run();
    }
}

Main java.

See below how to call the MyPostFile:

MyPostFile postFile = new MyPostFile();
try {
    postFile.run();
} catch (Exception e) {
    e.printStackTrace();
}

PHP

To receive the file is used the $_FILES. This feature allows the realization of uploads of text and binary files. At first it is validated if the file is blank: empty($_FILES), and if not, a filename is generated using date and time: date('YmdHis'). See the final code below:

if (empty($_FILES)) { // verifica se existe algum entrada de arquivo
        echo 'Erro ao enviar arquivo';
} else {   

    if (!empty($_FILES['file']) && $_FILES['file']['error'] !== 4) { 
            if (!$_FILES['file']['error']) {

                $temp = explode(".", $_FILES["file"]["name"]);
                $newfilename = "_".date('YmdHis') . '.' . end($temp);

                if (!move_uploaded_file($_FILES['file']['tmp_name'], $newfilename)) {
                    echo 'There is a error while processing uploaded file';
                }
            } else {
                echo 'Erro ao enviar arquivo';
            }
    }
}

PS.: For all of this to work properly, you cannot forget the permissions that must be granted on manifest.xml.

  • Thanks @Ack Lay, it worked for me.

  • @Emersonbarcellos for nothing... need, just call! =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.