Image upload using okHttp
You need to Use
new MultipartBody.Builder()
Instead of
new MultipartBuilder()
Its working
Upload an array of images using OkHTTP
My guess is that you need to change the name of the multipart data field to file[]
since the server expects an array of images and not a single (last) one:
buildernew.addFormDataPart("file[]", image.getName(), imageBody);
How I can upload photos by Uri instead of File in Android Q using okhttp
That was solved after issuing a comment: InputStreamRequestBody.
https://github.com/square/okhttp/issues/3585#issuecomment-327319196
File uploading on a PHP server using OkHttp, error?
To provide all deatails and what the problem was originally.
First of all everything works now.
The original issue ocurred when the image path provided was completly wrong, this was provided by the user inputting , however Glide could easily display it, so i did display it, then got the drawable convert it to bitmap and then byte[] and finally save the image by using FileOutStream to a cache created (cache is cleaned on the onStop() funstion), finally just use this.getCachedir()
to grap the image path.
Build the Multipart.Builder, and .addFormDataPart("fileToUpload", result + ".png",
RequestBody.create(MEDIA_TYPE_PNG, new File(imagePath)))
This way The PHP server can get "fileToUpload"
and store it, also the PHP file requires a directory to store the images, this case being the "images/", for that pre-create that directory so the PHP file recognizes it and stores it in.
For anyone that wants to use the same library and try to upload an image use the following code
For Java:
public String postImage (String imagePath) {
result = ""+ System.currentTimeMillis();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("fileToUpload", result + ".png",
RequestBody.create(MEDIA_TYPE_PNG, new File(imagePath)))
.build();
Request request = new Request.Builder()
.url("http://192.168.0.17/addImage.php")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
result = response.body().string();
}
}
});
return "http://192.168.0.17/uploads/"+result;
}
The PHP Server side:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}?>
Remember to set the Permissions on your Android App, and set the php.ini to allow file uploads.
okhttp multipart image upload with file name
Get OkHttp 2.1, and use MultipartBuilder.addFormDataPart()
which takes the filename as a parameter.
how to use okhttp to upload a file?
Note: this answer is for okhttp 1.x/2.x. For 3.x, see this other answer.
The class Multipart
from mimecraft encapsulates the whole HTTP body and can handle regular fields like so:
Multipart m = new Multipart.Builder()
.type(Multipart.Type.FORM)
.addPart(new Part.Builder()
.body("value")
.contentDisposition("form-data; name=\"non_file_field\"")
.build())
.addPart(new Part.Builder()
.contentType("text/csv")
.body(aFile)
.contentDisposition("form-data; name=\"file_field\"; filename=\"file1\"")
.build())
.build();
Take a look at examples of multipart/form-data encoding to get a sense of how you need to construct the parts.
Once you have a Multipart
object, all that's left to do is specify the right Content-Type
header and pass on the body bytes to the request.
Since you seem to be working with the v2.0 of the OkHttp API, which I don't have experience with, this is just guess code:
// You'll probably need to change the MediaType to use the Content-Type
// from the multipart object
Request.Body body = Request.Body.create(
MediaType.parse(m.getHeaders().get("Content-Type")),
out.toByteArray());
For OkHttp 1.5.4, here is a stripped down code I'm using which is adapted from a sample snippet:
OkHttpClient client = new OkHttpClient();
OutputStream out = null;
try {
URL url = new URL("http://www.example.com");
HttpURLConnection connection = client.open(url);
for (Map.Entry<String, String> entry : multipart.getHeaders().entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
connection.setRequestMethod("POST");
// Write the request.
out = connection.getOutputStream();
multipart.writeBodyTo(out);
out.close();
// Read the response.
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Unexpected HTTP response: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
}
} finally {
// Clean up.
try {
if (out != null) out.close();
} catch (Exception e) {
}
}
Related Topics
How to Get References for All Currently Active Fragments in an Activity
Identifying Rtl Language in Android
How to Change the Background Color Around a Dialogfragment
Get My Phone Number in Android
Gridview with Different Cells Sizes, Pinterest Style
Remove Bottomnavigationview Labels
Disable the Touch Events for All the Views
How to Have a Viewpager Inside of a Scrollview
Android: Using Objectanimator to Translate a View with Fractional Values of the View's Dimension
Android Tabwidget Detect Click on Current Tab
Android Calling Asynctask Right After an Another Finished
Android: Launch Activity from Clickable Text
How to Get Each Device's Ip Address in Wi-Fi Direct Scenario
Android 'Unable to Add Window -- Token Null Is Not for an Application' Exception
Two Textviews Side by Side, Only One to Ellipsize
Cordova Android Requirements Failed: "Could Not Find an Installed Version of Gradle"
How to Authenticate Two Types of Users (Student and Driver) in My Android App Using Firebase