Can you share the request you’re making? From the error message, it seems like the file isn’t being included.
Hi Daniel,
I use another method using OkHttp,
This one produces
E/Response: Response{protocol=http/1.1, code=400, message=Bad Request, url=”urlwithtoken”
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of(“Content-Disposition”, “form-data; name=\”title\””),
RequestBody.create(null, q[idx]))
.addPart(
Headers.of(“Content-Disposition”, “form-data; name=\”image\””),
RequestBody.create(MEDIA_TYPE_JPG, sourceFile))
.build();
While this one is 500
MediaType mediaType = MediaType.parse(“multipart/form-data; boundary=—011000010111000001101001”);
RequestBody body = RequestBody.create(mediaType, “—–011000010111000001101001\r\nContent-Disposition: form-data; name=\”fileName\”; filename=”+ sourceFile +”\r\nContent-Type: image/jpeg\r\n\r\n\r\n—–011000010111000001101001–“);
Request request = new Request.Builder()
.url(serverUri)
.post(body)
.addHeader(“content-type”, “multipart/form-data; boundary=—011000010111000001101001”)
.addHeader(“content-disposition”, String.valueOf(sourceFile))
.addHeader(“cache-control”, “no-cache”)
.build();
btw
I’m using postman to generate the the 2nd code which is ok.
I can upload image using PostMan.
Hi All,
I solve this problem and has nothing to do with wp rest api,
with the beta-2.8 just release I can now upload image to the server
using the media endpoints…
Below is the code I used with okHttp which you can compile via
gradle >>> compile ‘com.squareup.okhttp:okhttp:2.6.0’
OkHttpClient client = new OkHttpClient();
MediaType MEDIA_TYPE_JPG = MediaType.parse(“image/jpg”);
File sourceFile = new File(filepath);
Uri uri = new Uri.Builder()
.scheme(protocol)
.authority(domain)
.path(“wp-json/wp/v2/media”)
.appendQueryParameter(“access_token”, accessToken)
.build();
String serverUri = String.valueOf(uri);
String[] image = filepath.split(“/”);
int idx = image .length – 1;
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart(“file”, image [idx], RequestBody.create(MEDIA_TYPE_JPG, sourceFile))
.build();
Request request = new Request.Builder()
.url(serverUri)
.post(requestBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
Hope this helps…