Today I encountered an image upload interface. The backend access file is always null. If you look closely, it is ContentType: multipart/form-data. I don’t use much of this method, so I will record it here.
Preparation
First, make sure the project has added dependencies to the OkHttp3 library:
implementation '.okhttp3:okhttp:4.9.0'
ContentType Overview
ContentType, also known as media type or MIME type, is used to describe content types in network requests and responses.
Here are some common ContentTypes:
-
text/plain
: Normal text -
text/html
: HTML Documentation -
application/json
: JSON data -
application/xml
: XML data -
image/jpeg
: JPEG Pictures -
image/png
:PNG Pictures -
multipart/form-data
: Used for file upload
This article focuses onmultipart/form-data
, because it is often used for form submissions, especially forms containing file uploads.
step
1. Create MediaType
MediaType mediaType = ("image/jpeg");
MediaType
For description of file types, here we upload images in JPEG format.
2. Create a RequestBody
RequestBody fileBody = (mediaType, photoFile);
RequestBody
Used to encapsulate file data to be uploaded.
3. Create a MultipartBody
RequestBody requestBody = new () .setType() .addFormDataPart("file", (), fileBody) .build();
MultipartBody
For building multi-part form requests, the file section is added here.
4. Add a request header
I don't know why he puts the parameters in the url...
Request request = new () .url(":xxxxx/fileUploadAndDownload/upload?detailNo=1234&noSave=0") .addHeader("X-Token", token) .post(requestBody) .build();
Here we have added a custom request headerX-Token
。
5. Send a request
OkHttpClient client = new OkHttpClient(); (request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { (); } @Override public void onResponse(Call call, Response response) throws IOException { if (!()) { throw new IOException("Unexpected code " + response); } (().string()); } });
passOkHttpClient
Send a request and process the response.
Complete code
Use OkHttp3 tomultipart/form-data
Sample code for uploading images.
import okhttp3.*; import ; import ; import ; import ; public class UploadImage { private static final String TAG = "UploadImage"; public static void main(String[] args) { // Create MediaType MediaType mediaType = ("image/jpeg"); // Image file path File photoFile = new File("path/to/your/"); // Create RequestBody RequestBody fileBody = (mediaType, photoFile); // Create MultipartBody RequestBody requestBody = new () .setType() .addFormDataPart("file", (), fileBody) .build(); // Get custom request header Map<String, String> headers = ().getHeaders(); String token = ("X-Token"); Set<String> keySet = (); for (String key : keySet) { (TAG, "uploadImage: " + (key)); } // Create a Request Request request = new () .url("http://192.168.6.162:8888/fileUploadAndDownload/upload?detailNo=1234&noSave=0") .addHeader("X-Token", token) .post(requestBody) .build(); // Create OkHttpClient OkHttpClient client = new OkHttpClient(); // Send a request (request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { (); } @Override public void onResponse(Call call, Response response) throws IOException { if (!()) { throw new IOException("Unexpected code " + response); } // Process the response (().string()); } }); } }
I am using the EasyHttp library here. I don’t know how to set multipart/form-data, which causes EasyHttp to upload images.
That's why I used the native API to learn first. I'll post it here to upload pictures using multipart/form-data.
// Create a RequestBody, specify the media type and file RequestBody fileRequestBody = (("image/jpeg"), photoFile); // Create, specify the field name and RequestBody filePart = ("file", (), fileRequestBody); // Build MultipartBody MultipartBody requestBody = new () .setType() .addPart(filePart) .build(); (this) .api(new UploadApi()) .body(requestBody) .request(new OnUpdateListener<Void>() { @Override public void onUpdateProgressChange(int progress) { (TAG, "onUpdateProgressChange: "+progress); } @Override public void onUpdateSuccess(Void result) { (TAG, "onUpdateSuccess:"); } @Override public void onUpdateFail(Throwable throwable) { (TAG, "onUpdateFail:"); } });
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.