I’m using Loopj to upload files into my WordPress site and WP REST API v1 and/or v2 (same results).
The authentications goes great, headers goes great, file “uploads” but when I check it in my WordPress backend… the image or file is broken.
The Android part goes like this:
File myFile = new File(finalpath);
String name = Utils.getLastBitFromUrl(finalpath);
String extension = Utils.getFileExtention(finalpath);
client.setBasicAuth("myusername", "mypassword", new AuthScope("mywebsite.com", 80, AuthScope.ANY_REALM));
client.addHeader("Content-Disposition", "filename=" + name);
client.addHeader("Content-Type", "image/" + extension);
try {
params.put("data", myFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// or: http://mywebsite.com/wp-json/wp/v2/media for v2
client.post("http://mywebsite.com/wp-json/media", params, new AsyncHttpResponseHandler() {
int count = 0;
@Override
public void onStart() {
prgDialog = new ProgressDialog(MainActivity.this);
prgDialog.setMessage("Uploading Image...");
prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
prgDialog.setMax(100);
prgDialog.show();
}
@Override
public void onProgress(long bytesWritten, long totalSize) {
if(count < 1){
count++;
Log.d("size", "" + Utils.formatFileSize(totalSize));
}
long progressPercentage = (long)100*bytesWritten/totalSize;
if(progressPercentage <= 100) {
prgDialog.setProgress((int) progressPercentage);
}
}
@Override
public void onSuccess(int statuscode, Header[] headers, byte[] response) {
try {
prgDialog.dismiss();
JSONObject obj = new JSONObject(Utils.decodeUTF8(response));
Log.e("success!", Utils.decodeUTF8(response));
} catch (JSONException e) {
e.printStackTrace();
}
But the image… looks like this in my WordPress backend:
Does anyone have any idea why this happen? My file and File Path are perfect. I can get the image and show it on my phone before upload it.
EDIT: This cURL works perfect
curl -i -X POST -H "Content-Disposition:filename=test.png" --data-binary @"/home/my-name/Downloads/example.png" -d title="test" -u username:password -H "Expect:" http://my.website.com/wp-json/wp/v2/media
The main difference is over –data-binary @ but I don’t know how to do that over Java.
I think your image not attached properly . Please check with postman check my screenshot below