How to upload the .db file (SQLite backup) from the android device to a server using the Okhttp, java, and PHP library?
How to upload the .db file (SQLite backup) from the android device to a server using the Okhttp, java, and PHP library?
At OkHttp Recipes documentation there are some common demonstrations. More specifically, you will have to use properties of class MultipartBody.Builder()
to send the file.
No square / okhttp has exactly what you want ( PostFile.java
), however for what you need, I did some basic changes. I'll show you:
This is the class that makes it all 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();
}
}
See below how to call MyPostFile
:
MyPostFile postFile = new MyPostFile();
try {
postFile.run();
} catch (Exception e) {
e.printStackTrace();
}
$_FILES
is used to receive the file. This feature allows uploads of text and binary files. At first it is validated if the file is blank: empty($_FILES)
, and if it is 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 can not forget the permissions that should be granted in manifest.xml
.