根据图像大小,您可以将其转换为Base64编码,并在正文中使用标准上传内容。
如果要上传大文件,则应坚持使用多部分上传,在这种情况下,它将作为文件进行发送,但您必须指定文件类型,API需要适当解析。有许多出色的库可帮助您完成此操作,如OKHTTP,Retro也将利用此库。
但是,图像、文档和视频在传输层上都只是文件,只需要在调用中为图像提供适当的请求类型,以帮助API适当处理。
这是他们教程中的内容:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
service = new Retrofit.Builder().baseUrl("http://192.168.0.234:3000").client(client).build().create(Service.class);
.
.
.
File file = new File(filePath);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");
retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body, name);
req.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
如果文件不太大,可以使用Base64编码。
public class Base64EncodeMediaAsyncTask extends AsyncTask<Void, Void, MediaModel> {
private static final String TAG = Globals.SEARCH_STRING + Base64EncodeMediaAsyncTask.class.getSimpleName();
private Context mContext;
private MediaModel mMediaModelToConvert;
public Base64EncodeMediaAsyncTask(Context context, MediaModel model){
mContext = context;
mMediaModelToConvert = model;
}
@Override
protected MediaModel doInBackground(Void... params) {
try{
InputStream inputStream = new FileInputStream(mMediaModelToConvert.getAbsoluteLocalPath());
byte[] bytes;
byte[] buffer = new byte[(int) new File(mMediaModelToConvert.getAbsoluteLocalPath()).length()];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
bytes = output.toByteArray();
mMediaModelToConvert.setBase64String(Base64.encodeToString(bytes, Base64.DEFAULT));
}catch (Exception ex){
A35Log.e(TAG, "Failed to get base 64 encoding for file: " + mMediaModelToConvert.getAbsoluteLocalPath());
return null;
}
return mMediaModelToConvert;
}
@Override
protected void onPostExecute(MediaModel success) {
super.onPostExecute(success);
}
}
请忽略我用于包装其他内容的复杂对象MediaModel,只使用标准文件(即指向您的图像的指针)