POST 使用 Retrofit 2.0 的多部分表单数据,包括图像
POST Multipart Form Data using Retrofit 2.0 including image
我正在尝试使用 Retrofit 2.0
对服务器执行 HTTP POST
MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/*");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG,90,byteArrayOutputStream);
profilePictureByte = byteArrayOutputStream.toByteArray();
Call<APIResults> call = ServiceAPI.updateProfile(
RequestBody.create(MEDIA_TYPE_TEXT, emailString),
RequestBody.create(MEDIA_TYPE_IMAGE, profilePictureByte));
call.enqueue();
服务器 returns 一个错误,指出文件无效。
这很奇怪,因为我曾尝试在 iOS(使用其他库)上上传具有相同格式的相同文件,但上传成功。
我想知道使用 Retrofit 2.0 上传图片的正确方法是什么?
我应该先存盘再上传吗?
P.S.: 我已经对其他不包含图像的多部分请求进行了改造,它们成功完成了。问题是当我试图在正文中包含一个字节时。
我强调了 1.9 和 2.0 中的解决方案,因为它对某些人很有用
在1.9
中,我认为更好的解决方案是将文件保存到磁盘并将其用作类型文件,如:
改装 1.9
(我不知道你的 server-side 实现)有一个 API 接口方法类似于这个
@POST("/en/Api/Results/UploadFile")
void UploadFile(@Part("file") TypedFile file,
@Part("folder") String folder,
Callback<Response> callback);
并像
一样使用它
TypedFile file = new TypedFile("multipart/form-data",
new File(path));
对于RetroFit 2使用下面的方法
RetroFit 2.0(这是 issue in RetroFit 2 which is fixed now, for the correct method refer 的解决方法)
API接口:
public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser(@Header("Authorization") String authorization,
@Part("file\"; filename=\"pp.png\" ") RequestBody file,
@Part("FirstName") RequestBody fname,
@Part("Id") RequestBody id);
}
像这样使用它:
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"),
file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"),
firstNameField.getText()
.toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"),
AZUtils.getUserId(this));
Call<User> call = client.editUser(AZUtils.getToken(this),
fbody,
name,
id);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response,
Retrofit retrofit) {
AZUtils.printObject(response.body());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
更新Retrofit2.0
中上传图片文件的代码
public interface ApiInterface {
@Multipart
@POST("user/signup")
Call<UserModelResponse> updateProfilePhotoProcess(@Part("email") RequestBody email,
@Part("password") RequestBody password,
@Part("profile_pic\"; filename=\"pp.png")
RequestBody file);
}
将MediaType.parse("image/*")
更改为MediaType.parse("image/jpeg")
RequestBody reqFile = RequestBody.create(MediaType.parse("image/jpeg"),
file);
RequestBody email = RequestBody.create(MediaType.parse("text/plain"),
"upload_test4@gmail.com");
RequestBody password = RequestBody.create(MediaType.parse("text/plain"),
"123456789");
Call<UserModelResponse> call = apiService.updateProfilePhotoProcess(email,
password,
reqFile);
call.enqueue(new Callback<UserModelResponse>() {
@Override
public void onResponse(Call<UserModelResponse> call,
Response<UserModelResponse> response) {
String
TAG =
response.body()
.toString();
UserModelResponse userModelResponse = response.body();
UserModel userModel = userModelResponse.getUserModel();
Log.d("MainActivity",
"user image = " + userModel.getProfilePic());
}
@Override
public void onFailure(Call<UserModelResponse> call,
Throwable t) {
Toast.makeText(MainActivity.this,
"" + TAG,
Toast.LENGTH_LONG)
.show();
}
});
有一种 正确 上传文件的方法 Retrofit 2,没有任何 hack:
定义API接口:
@Multipart
@POST("uploadAttachment")
Call<MyResponse> uploadAttachment(@Part MultipartBody.Part filePart);
// You can add other parameters too
像这样上传文件:
File file = // initialize file here
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<MyResponse> call = api.uploadAttachment(filePart);
这里只演示文件上传,您也可以在同一个方法中添加其他参数@Part
注解
我为我的注册用户使用了 Retrofit 2.0,从注册帐户发送 multipart/form 文件图像和文本
在我的 RegisterActivity 中,使用 AsyncTask
//AsyncTask
private class Register extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {..}
@Override
protected String doInBackground(String... params) {
new com.tequilasoft.mesasderegalos.dbo.Register().register(txtNombres, selectedImagePath, txtEmail, txtPassword);
responseMensaje = StaticValues.mensaje ;
mensajeCodigo = StaticValues.mensajeCodigo;
return String.valueOf(StaticValues.code);
}
@Override
protected void onPostExecute(String codeResult) {..}
而在我的 Register.java class 中使用 Retrofit 进行同步调用
import android.util.Log;
import com.tequilasoft.mesasderegalos.interfaces.RegisterService;
import com.tequilasoft.mesasderegalos.utils.StaticValues;
import com.tequilasoft.mesasderegalos.utils.Utilities;
import java.io.File;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
/**Created by sam on 2/09/16.*/
public class Register {
public void register(String nombres, String selectedImagePath, String email, String password){
try {
// create upload service client
RegisterService service = ServiceGenerator.createUser(RegisterService.class);
// add another part within the multipart request
RequestBody requestEmail =
RequestBody.create(
MediaType.parse("multipart/form-data"), email);
// add another part within the multipart request
RequestBody requestPassword =
RequestBody.create(
MediaType.parse("multipart/form-data"), password);
// add another part within the multipart request
RequestBody requestNombres =
RequestBody.create(
MediaType.parse("multipart/form-data"), nombres);
MultipartBody.Part imagenPerfil = null;
if(selectedImagePath!=null){
File file = new File(selectedImagePath);
Log.i("Register","Nombre del archivo "+file.getName());
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
imagenPerfil = MultipartBody.Part.createFormData("imagenPerfil", file.getName(), requestFile);
}
// finally, execute the request
Call<ResponseBody> call = service.registerUser(imagenPerfil, requestEmail,requestPassword,requestNombres);
Response<ResponseBody> bodyResponse = call.execute();
StaticValues.code = bodyResponse.code();
StaticValues.mensaje = bodyResponse.message();
ResponseBody errorBody = bodyResponse.errorBody();
StaticValues.mensajeCodigo = errorBody==null
?null
:Utilities.mensajeCodigoDeLaRespuestaJSON(bodyResponse.errorBody().byteStream());
Log.i("Register","Code "+StaticValues.code);
Log.i("Register","mensaje "+StaticValues.mensaje);
Log.i("Register","mensajeCodigo "+StaticValues.mensaje);
}
catch (Exception e){
e.printStackTrace();
}
}
}
RegisterService接口中
public interface RegisterService {
@Multipart
@POST(StaticValues.REGISTER)
Call<ResponseBody> registerUser(@Part MultipartBody.Part image,
@Part("email") RequestBody email,
@Part("password") RequestBody password,
@Part("nombre") RequestBody nombre
);
}
对于 InputStream 响应的 Utilities 解析
public class Utilities {
public static String mensajeCodigoDeLaRespuestaJSON(InputStream inputStream){
String mensajeCodigo = null;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
inputStream.close();
mensajeCodigo = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return mensajeCodigo;
}
}
添加@insomniac给出的答案。您可以创建一个 Map
来放置 RequestBody
的参数,包括图像。
接口代码
public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser (@Header("Authorization") String authorization, @PartMap Map<String, RequestBody> map);
}
代码 Java class
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
Map<String, RequestBody> map = new HashMap<>();
map.put("file\"; filename=\"pp.png\" ", fbody);
map.put("FirstName", name);
map.put("Id", id);
Call<User> call = client.editUser(AZUtils.getToken(this), map);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response, Retrofit retrofit)
{
AZUtils.printObject(response.body());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
使用 Retrofit 上传文件非常简单您需要将 api 界面构建为
public interface Api {
String BASE_URL = "http://192.168.43.124/ImageUploadApi/";
@Multipart
@POST("yourapipath")
Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);
}
在上面的代码中 image 是键名所以如果你使用 php 你会写 $_FILES['image' ]['tmp_name'] 得到这个。
filename="myfile.jpg" 是随请求一起发送的文件的名称。
现在要上传文件,您需要一种方法来为您提供来自 Uri 的绝对路径。
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
现在您可以使用以下代码上传您的文件。
private void uploadFile(Uri fileUri, String desc) {
//creating a file
File file = new File(getRealPathFromURI(fileUri));
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
更详细的解释可以访问这个Retrofit Upload File Tutorial.
所以这是完成任务的非常简单的方法。您需要按照以下步骤操作:-
1.第一步
public interface APIService {
@Multipart
@POST("upload")
Call<ResponseBody> upload(
@Part("item") RequestBody description,
@Part("imageNumber") RequestBody description,
@Part MultipartBody.Part imageFile
);
}
您需要将整个调用设为 @Multipart request
。 item
和 image number
只是包裹在 RequestBody
中的字符串主体。我们使用 MultipartBody.Part class
允许我们在请求
中发送除二进制文件数据之外的实际文件名
2。第二步
File file = (File) params[0];
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body =MultipartBody.Part.createFormData("Image", file.getName(), requestBody);
RequestBody ItemId = RequestBody.create(okhttp3.MultipartBody.FORM, "22");
RequestBody ImageNumber = RequestBody.create(okhttp3.MultipartBody.FORM,"1");
final Call<UploadImageResponse> request = apiService.uploadItemImage(body, ItemId,ImageNumber);
现在你有 image path
,你需要转换成 file
。现在使用方法 RequestBody.create(MediaType.parse("multipart/form-data"), file)
将 file
转换成 RequestBody
。现在您需要使用方法 MultipartBody.Part.createFormData("Image", file.getName(), requestBody);
将 RequestBody requestFile
转换为 MultipartBody.Part
。
ImageNumber
和 ItemId
是我需要发送到服务器的另一个数据,所以我也将两者都变成了 RequestBody
.
Kotlin 版本更新 RequestBody.create
:
改造界面
@Multipart
@POST("uploadPhoto")
fun uploadFile(@Part file: MultipartBody.Part): Call<FileResponse>
并上传
fun uploadFile(fileUrl: String){
val file = File(fileUrl)
val fileUploadService = RetrofitClientInstance.retrofitInstance.create(FileUploadService::class.java)
val requestBody = file.asRequestBody(file.extension.toMediaTypeOrNull())
val filePart = MultipartBody.Part.createFormData(
"blob",file.name,requestBody
)
val call = fileUploadService.uploadFile(filePart)
call.enqueue(object: Callback<FileResponse>{
override fun onFailure(call: Call<FileResponse>, t: Throwable) {
Log.d(TAG,"Fckd")
}
override fun onResponse(call: Call<FileResponse>, response: Response<FileResponse>) {
Log.d(TAG,"success"+response.toString()+" "+response.body().toString()+" "+response.body()?.status)
}
})
}
感谢@jimmy0251
不要在函数名中使用多个参数只使用简单的几个参数约定,这将增加代码的可读性,为此你可以这样做 -
// MultipartBody.Part.createFormData("partName", data)
Call<SomReponse> methodName(@Part MultiPartBody.Part part);
// RequestBody.create(MediaType.get("text/plain"), data)
Call<SomReponse> methodName(@Part(value = "partName") RequestBody part);
/* for single use or you can use by Part name with Request body */
// add multiple list of part as abstraction |ease of readability|
Call<SomReponse> methodName(@Part List<MultiPartBody.Part> parts);
Call<SomReponse> methodName(@PartMap Map<String, RequestBody> parts);
// this way you will save the abstraction of multiple parts.
在使用 Retrofit 时可能会遇到 多个异常,所有异常都记录为代码,有一个演练到 retrofit2/RequestFactory.java
。你可以使用两个函数 parseParameterAnnotation
和 parseMethodAnnotation
可以抛出异常的地方,请通过这个,它会比 googling/Whosebug[= 节省你很多时间23=]
在 kotlin 中非常简单,使用 toMediaType、asRequestBody[= 的扩展方法26=] 和 toRequestBody 这是一个例子:
在这里,我使用 multipart
发布了几个普通字段以及一个 pdf 文件和一个图像文件
这是 API 使用改装的声明:
@Multipart
@POST("api/Lesson/AddNewLesson")
fun createLesson(
@Part("userId") userId: RequestBody,
@Part("LessonTitle") lessonTitle: RequestBody,
@Part pdf: MultipartBody.Part,
@Part imageFile: MultipartBody.Part
): Maybe<BaseResponse<String>>
实际调用方法如下:
api.createLesson(
userId.toRequestBody("text/plain".toMediaType()),
lessonTitle.toRequestBody("text/plain".toMediaType()),
startFromRegister.toString().toRequestBody("text/plain".toMediaType()),
MultipartBody.Part.createFormData(
"jpeg",
imageFile.name,
imageFile.asRequestBody("image/*".toMediaType())
),
MultipartBody.Part.createFormData(
"pdf",
pdfFile.name,
pdfFile.asRequestBody("application/pdf".toMediaType())
)
* Return MultipartBody from file path
public static MultipartBody.Part generateFileBody(String imagePath)
{
File file = new File(imagePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
return MultipartBody.Part.createFormData("mediaProfilePic", file.getName(), requestFile);
}
requestBody可以用来上传
val body: RequestBody = Builder().setType(MultipartBody.FORM)
.addFormDataPart(
"file", "<image name you wish to give>",
RequestBody.create(
MediaType.parse("application/octet-stream"),
File(path)
)
)
.build()
uploadProfilePhoto(body)
然后这样调用:
@POST("/**")
suspend fun uploadProfilePhoto(
@Body body: RequestBody,
): ResponseBody
}
就我而言,我需要发送一个 PDF 文件 (application/pdf
),以及 JSON 信息 (application/json
)。值得庆幸的是,Retrofit2 使这变得超级简单。
我的界面如下所示:
interface MyApi {
@Multipart
@POST("upload")
fun uploadPDF(
@Part file: MultipartBody.Part,
@Part(value = "jsoninfo") jsoninfo: MyJsonObject
): Call<MyResponse>
}
其中 jsoninfo
是我的 JSON 数据的名称,MyJsonObject
是我的数据 class,MyResponse
是我期待的响应,当然。
然后,我只需按如下方式调用 API 方法:
val myJsonObject = MyJsonObject(...)
// "file" is of type byte[] already
val requestBody = RequestBody.create(file, MediaType.parse("application/pdf"))
val filePart = MultipartBody.Part.createFormData("file", "myfile.pdf", requestBody)
api.uploadPDF(filePart, myJsonObject).enqueue(...)
我正在尝试使用 Retrofit 2.0
对服务器执行 HTTP POSTMediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");
MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/*");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG,90,byteArrayOutputStream);
profilePictureByte = byteArrayOutputStream.toByteArray();
Call<APIResults> call = ServiceAPI.updateProfile(
RequestBody.create(MEDIA_TYPE_TEXT, emailString),
RequestBody.create(MEDIA_TYPE_IMAGE, profilePictureByte));
call.enqueue();
服务器 returns 一个错误,指出文件无效。
这很奇怪,因为我曾尝试在 iOS(使用其他库)上上传具有相同格式的相同文件,但上传成功。
我想知道使用 Retrofit 2.0 上传图片的正确方法是什么?
我应该先存盘再上传吗?
P.S.: 我已经对其他不包含图像的多部分请求进行了改造,它们成功完成了。问题是当我试图在正文中包含一个字节时。
我强调了 1.9 和 2.0 中的解决方案,因为它对某些人很有用
在1.9
中,我认为更好的解决方案是将文件保存到磁盘并将其用作类型文件,如:
改装 1.9
(我不知道你的 server-side 实现)有一个 API 接口方法类似于这个
@POST("/en/Api/Results/UploadFile")
void UploadFile(@Part("file") TypedFile file,
@Part("folder") String folder,
Callback<Response> callback);
并像
一样使用它TypedFile file = new TypedFile("multipart/form-data",
new File(path));
对于RetroFit 2使用下面的方法
RetroFit 2.0(这是 issue in RetroFit 2 which is fixed now, for the correct method refer 的解决方法)
API接口:
public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser(@Header("Authorization") String authorization,
@Part("file\"; filename=\"pp.png\" ") RequestBody file,
@Part("FirstName") RequestBody fname,
@Part("Id") RequestBody id);
}
像这样使用它:
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"),
file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"),
firstNameField.getText()
.toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"),
AZUtils.getUserId(this));
Call<User> call = client.editUser(AZUtils.getToken(this),
fbody,
name,
id);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response,
Retrofit retrofit) {
AZUtils.printObject(response.body());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
更新Retrofit2.0
中上传图片文件的代码public interface ApiInterface {
@Multipart
@POST("user/signup")
Call<UserModelResponse> updateProfilePhotoProcess(@Part("email") RequestBody email,
@Part("password") RequestBody password,
@Part("profile_pic\"; filename=\"pp.png")
RequestBody file);
}
将MediaType.parse("image/*")
更改为MediaType.parse("image/jpeg")
RequestBody reqFile = RequestBody.create(MediaType.parse("image/jpeg"),
file);
RequestBody email = RequestBody.create(MediaType.parse("text/plain"),
"upload_test4@gmail.com");
RequestBody password = RequestBody.create(MediaType.parse("text/plain"),
"123456789");
Call<UserModelResponse> call = apiService.updateProfilePhotoProcess(email,
password,
reqFile);
call.enqueue(new Callback<UserModelResponse>() {
@Override
public void onResponse(Call<UserModelResponse> call,
Response<UserModelResponse> response) {
String
TAG =
response.body()
.toString();
UserModelResponse userModelResponse = response.body();
UserModel userModel = userModelResponse.getUserModel();
Log.d("MainActivity",
"user image = " + userModel.getProfilePic());
}
@Override
public void onFailure(Call<UserModelResponse> call,
Throwable t) {
Toast.makeText(MainActivity.this,
"" + TAG,
Toast.LENGTH_LONG)
.show();
}
});
有一种 正确 上传文件的方法 Retrofit 2,没有任何 hack:
定义API接口:
@Multipart
@POST("uploadAttachment")
Call<MyResponse> uploadAttachment(@Part MultipartBody.Part filePart);
// You can add other parameters too
像这样上传文件:
File file = // initialize file here
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
Call<MyResponse> call = api.uploadAttachment(filePart);
这里只演示文件上传,您也可以在同一个方法中添加其他参数@Part
注解
我为我的注册用户使用了 Retrofit 2.0,从注册帐户发送 multipart/form 文件图像和文本
在我的 RegisterActivity 中,使用 AsyncTask
//AsyncTask
private class Register extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {..}
@Override
protected String doInBackground(String... params) {
new com.tequilasoft.mesasderegalos.dbo.Register().register(txtNombres, selectedImagePath, txtEmail, txtPassword);
responseMensaje = StaticValues.mensaje ;
mensajeCodigo = StaticValues.mensajeCodigo;
return String.valueOf(StaticValues.code);
}
@Override
protected void onPostExecute(String codeResult) {..}
而在我的 Register.java class 中使用 Retrofit 进行同步调用
import android.util.Log;
import com.tequilasoft.mesasderegalos.interfaces.RegisterService;
import com.tequilasoft.mesasderegalos.utils.StaticValues;
import com.tequilasoft.mesasderegalos.utils.Utilities;
import java.io.File;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
/**Created by sam on 2/09/16.*/
public class Register {
public void register(String nombres, String selectedImagePath, String email, String password){
try {
// create upload service client
RegisterService service = ServiceGenerator.createUser(RegisterService.class);
// add another part within the multipart request
RequestBody requestEmail =
RequestBody.create(
MediaType.parse("multipart/form-data"), email);
// add another part within the multipart request
RequestBody requestPassword =
RequestBody.create(
MediaType.parse("multipart/form-data"), password);
// add another part within the multipart request
RequestBody requestNombres =
RequestBody.create(
MediaType.parse("multipart/form-data"), nombres);
MultipartBody.Part imagenPerfil = null;
if(selectedImagePath!=null){
File file = new File(selectedImagePath);
Log.i("Register","Nombre del archivo "+file.getName());
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
imagenPerfil = MultipartBody.Part.createFormData("imagenPerfil", file.getName(), requestFile);
}
// finally, execute the request
Call<ResponseBody> call = service.registerUser(imagenPerfil, requestEmail,requestPassword,requestNombres);
Response<ResponseBody> bodyResponse = call.execute();
StaticValues.code = bodyResponse.code();
StaticValues.mensaje = bodyResponse.message();
ResponseBody errorBody = bodyResponse.errorBody();
StaticValues.mensajeCodigo = errorBody==null
?null
:Utilities.mensajeCodigoDeLaRespuestaJSON(bodyResponse.errorBody().byteStream());
Log.i("Register","Code "+StaticValues.code);
Log.i("Register","mensaje "+StaticValues.mensaje);
Log.i("Register","mensajeCodigo "+StaticValues.mensaje);
}
catch (Exception e){
e.printStackTrace();
}
}
}
RegisterService接口中
public interface RegisterService {
@Multipart
@POST(StaticValues.REGISTER)
Call<ResponseBody> registerUser(@Part MultipartBody.Part image,
@Part("email") RequestBody email,
@Part("password") RequestBody password,
@Part("nombre") RequestBody nombre
);
}
对于 InputStream 响应的 Utilities 解析
public class Utilities {
public static String mensajeCodigoDeLaRespuestaJSON(InputStream inputStream){
String mensajeCodigo = null;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
inputStream.close();
mensajeCodigo = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return mensajeCodigo;
}
}
添加@insomniac给出的答案。您可以创建一个 Map
来放置 RequestBody
的参数,包括图像。
接口代码
public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser (@Header("Authorization") String authorization, @PartMap Map<String, RequestBody> map);
}
代码 Java class
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
Map<String, RequestBody> map = new HashMap<>();
map.put("file\"; filename=\"pp.png\" ", fbody);
map.put("FirstName", name);
map.put("Id", id);
Call<User> call = client.editUser(AZUtils.getToken(this), map);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response, Retrofit retrofit)
{
AZUtils.printObject(response.body());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
使用 Retrofit 上传文件非常简单您需要将 api 界面构建为
public interface Api {
String BASE_URL = "http://192.168.43.124/ImageUploadApi/";
@Multipart
@POST("yourapipath")
Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);
}
在上面的代码中 image 是键名所以如果你使用 php 你会写 $_FILES['image' ]['tmp_name'] 得到这个。 filename="myfile.jpg" 是随请求一起发送的文件的名称。
现在要上传文件,您需要一种方法来为您提供来自 Uri 的绝对路径。
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
现在您可以使用以下代码上传您的文件。
private void uploadFile(Uri fileUri, String desc) {
//creating a file
File file = new File(getRealPathFromURI(fileUri));
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
更详细的解释可以访问这个Retrofit Upload File Tutorial.
所以这是完成任务的非常简单的方法。您需要按照以下步骤操作:-
1.第一步
public interface APIService {
@Multipart
@POST("upload")
Call<ResponseBody> upload(
@Part("item") RequestBody description,
@Part("imageNumber") RequestBody description,
@Part MultipartBody.Part imageFile
);
}
您需要将整个调用设为 @Multipart request
。 item
和 image number
只是包裹在 RequestBody
中的字符串主体。我们使用 MultipartBody.Part class
允许我们在请求
2。第二步
File file = (File) params[0];
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body =MultipartBody.Part.createFormData("Image", file.getName(), requestBody);
RequestBody ItemId = RequestBody.create(okhttp3.MultipartBody.FORM, "22");
RequestBody ImageNumber = RequestBody.create(okhttp3.MultipartBody.FORM,"1");
final Call<UploadImageResponse> request = apiService.uploadItemImage(body, ItemId,ImageNumber);
现在你有 image path
,你需要转换成 file
。现在使用方法 RequestBody.create(MediaType.parse("multipart/form-data"), file)
将 file
转换成 RequestBody
。现在您需要使用方法 MultipartBody.Part.createFormData("Image", file.getName(), requestBody);
将 RequestBody requestFile
转换为 MultipartBody.Part
。
ImageNumber
和 ItemId
是我需要发送到服务器的另一个数据,所以我也将两者都变成了 RequestBody
.
Kotlin 版本更新 RequestBody.create
:
改造界面
@Multipart
@POST("uploadPhoto")
fun uploadFile(@Part file: MultipartBody.Part): Call<FileResponse>
并上传
fun uploadFile(fileUrl: String){
val file = File(fileUrl)
val fileUploadService = RetrofitClientInstance.retrofitInstance.create(FileUploadService::class.java)
val requestBody = file.asRequestBody(file.extension.toMediaTypeOrNull())
val filePart = MultipartBody.Part.createFormData(
"blob",file.name,requestBody
)
val call = fileUploadService.uploadFile(filePart)
call.enqueue(object: Callback<FileResponse>{
override fun onFailure(call: Call<FileResponse>, t: Throwable) {
Log.d(TAG,"Fckd")
}
override fun onResponse(call: Call<FileResponse>, response: Response<FileResponse>) {
Log.d(TAG,"success"+response.toString()+" "+response.body().toString()+" "+response.body()?.status)
}
})
}
感谢@jimmy0251
不要在函数名中使用多个参数只使用简单的几个参数约定,这将增加代码的可读性,为此你可以这样做 -
// MultipartBody.Part.createFormData("partName", data)
Call<SomReponse> methodName(@Part MultiPartBody.Part part);
// RequestBody.create(MediaType.get("text/plain"), data)
Call<SomReponse> methodName(@Part(value = "partName") RequestBody part);
/* for single use or you can use by Part name with Request body */
// add multiple list of part as abstraction |ease of readability|
Call<SomReponse> methodName(@Part List<MultiPartBody.Part> parts);
Call<SomReponse> methodName(@PartMap Map<String, RequestBody> parts);
// this way you will save the abstraction of multiple parts.
在使用 Retrofit 时可能会遇到 多个异常,所有异常都记录为代码,有一个演练到 retrofit2/RequestFactory.java
。你可以使用两个函数 parseParameterAnnotation
和 parseMethodAnnotation
可以抛出异常的地方,请通过这个,它会比 googling/Whosebug[= 节省你很多时间23=]
在 kotlin 中非常简单,使用 toMediaType、asRequestBody[= 的扩展方法26=] 和 toRequestBody 这是一个例子:
在这里,我使用 multipart
发布了几个普通字段以及一个 pdf 文件和一个图像文件这是 API 使用改装的声明:
@Multipart
@POST("api/Lesson/AddNewLesson")
fun createLesson(
@Part("userId") userId: RequestBody,
@Part("LessonTitle") lessonTitle: RequestBody,
@Part pdf: MultipartBody.Part,
@Part imageFile: MultipartBody.Part
): Maybe<BaseResponse<String>>
实际调用方法如下:
api.createLesson(
userId.toRequestBody("text/plain".toMediaType()),
lessonTitle.toRequestBody("text/plain".toMediaType()),
startFromRegister.toString().toRequestBody("text/plain".toMediaType()),
MultipartBody.Part.createFormData(
"jpeg",
imageFile.name,
imageFile.asRequestBody("image/*".toMediaType())
),
MultipartBody.Part.createFormData(
"pdf",
pdfFile.name,
pdfFile.asRequestBody("application/pdf".toMediaType())
)
* Return MultipartBody from file path
public static MultipartBody.Part generateFileBody(String imagePath)
{
File file = new File(imagePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
return MultipartBody.Part.createFormData("mediaProfilePic", file.getName(), requestFile);
}
requestBody可以用来上传
val body: RequestBody = Builder().setType(MultipartBody.FORM)
.addFormDataPart(
"file", "<image name you wish to give>",
RequestBody.create(
MediaType.parse("application/octet-stream"),
File(path)
)
)
.build()
uploadProfilePhoto(body)
然后这样调用:
@POST("/**")
suspend fun uploadProfilePhoto(
@Body body: RequestBody,
): ResponseBody
}
就我而言,我需要发送一个 PDF 文件 (application/pdf
),以及 JSON 信息 (application/json
)。值得庆幸的是,Retrofit2 使这变得超级简单。
我的界面如下所示:
interface MyApi {
@Multipart
@POST("upload")
fun uploadPDF(
@Part file: MultipartBody.Part,
@Part(value = "jsoninfo") jsoninfo: MyJsonObject
): Call<MyResponse>
}
其中 jsoninfo
是我的 JSON 数据的名称,MyJsonObject
是我的数据 class,MyResponse
是我期待的响应,当然。
然后,我只需按如下方式调用 API 方法:
val myJsonObject = MyJsonObject(...)
// "file" is of type byte[] already
val requestBody = RequestBody.create(file, MediaType.parse("application/pdf"))
val filePart = MultipartBody.Part.createFormData("file", "myfile.pdf", requestBody)
api.uploadPDF(filePart, myJsonObject).enqueue(...)