我有一个邮差如下图。如何在Retrofit 2中做同样的事情。
我已经宣布了这样的界面。
@Multipart
@POST("/api/Pharmarcy/UploadImage")
Call<ResponseBody> uploadPrescriptionImage(
@Query("accessToken") String token,
@Query("pharmarcyRequestId") int pharmacyRequestedId,
@Part MultipartBody.Part image);
答案 0 :(得分:69)
@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
@Part("full_name") RequestBody fullName,
@Part MultipartBody.Part image,
@Part("other") RequestBody other);
//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// add another part within the multipart request
RequestBody fullName =
RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");
service.updateProfile(id, fullName, body, other);
看看我传递multipart和string参数的方式。希望这会对你有所帮助!
答案 1 :(得分:6)
http://mushtaq.16mb.com/retrofit_example/uploads/
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class AppConfig {
private static String BASE_URL = "http://mushtaq.16mb.com/";
static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
========================================================
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
interface ApiConfig {
@Multipart
@POST("retrofit_example/upload_image.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,
@Part("file") RequestBody name);
/*@Multipart
@POST("ImageUpload")
Call<ServerResponseKeshav> uploadFile(@Part MultipartBody.Part file,
@Part("file") RequestBody name);*/
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call<ServerResponse> uploadMulFile(@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}
//https://drive.google.com/open?id=0BzBKpZ4nzNzUMnJfaklVVTJkWEk
答案 2 :(得分:6)
对于具有inputStream的用户,您可以使用Multipart
上传inputStream。
@Multipart
@POST("pictures")
suspend fun uploadPicture(
@Part part: MultipartBody.Part
): NetworkPicture
然后在您的存储库类中:
suspend fun upload(inputStream: InputStream) {
val part = MultipartBody.Part.createFormData(
"pic", "myPic", RequestBody.create(
MediaType.parse("image/*"),
inputStream.readBytes()
)
)
uploadPicture(part)
}
要获得输入流,您可以执行类似的操作。
在片段或活动中,您需要创建一个返回InputStream
的图像选择器。 InputStream的优点是它可用于云驱动器上的文件,例如google驱动器和保管箱。
从pickImage()
或View.OnClickListener
呼叫onOptionsItemSelected
。
private fun pickImage() {
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
startActivityForResult(intent, PICK_PHOTO)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_PHOTO && resultCode == Activity.RESULT_OK) {
try {
data?.let {
val inputStream: InputStream? =
context?.contentResolver?.openInputStream(it.data!!)
inputStream?.let { stream ->
itemViewModel.uploadPicture(stream)
}
}
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
}
}
companion object {
const val PICK_PHOTO = 1
}
答案 3 :(得分:1)
使用Retrofit 2.0您可以使用:
@Multipart
@POST("uploadImage")
Call<ResponseBody> uploadImage(@Part("file\"; fileName=\"myFile.png\" ")RequestBody requestBodyFile, @Part("image") RequestBody requestBodyJson);
提出请求:
File imgFile = new File("YOUR IMAGE FILE PATH");
RequestBody requestBodyFile = RequestBody.create(MediaType.parse("image/*"), imgFile);
RequestBody requestBodyJson = RequestBody.create(MediaType.parse("text/plain"),
retrofitClient.getJsonObject(uploadRequest));
//make sync call
Call<ResponseBody> uploadBundle = uploadImpl.uploadImage(requestBodyFile, requestBodyJson);
Response<BaseResponse> response = uploadBundle.execute();
答案 4 :(得分:1)
@Multipart
@POST(Config.UPLOAD_IMAGE)
Observable<Response<String>> uploadPhoto(@Header("Access-Token") String header, @Part MultipartBody.Part imageFile);
你可以这样称呼api:
public void uploadImage(File file) {
// create multipart
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// upload
getViewInteractor().showProfileUploadingProgress();
Observable<Response<String>> observable = api.uploadPhoto("",body);
// on Response
subscribeForNetwork(observable, new ApiObserver<Response<String>>() {
@Override
public void onError(Throwable e) {
getViewInteractor().hideProfileUploadingProgress();
}
@Override
public void onResponse(Response<String> response) {
if (response.code() != 200) {
Timber.d("error " + response.code());
return;
}
getViewInteractor().hideProfileUploadingProgress();
getViewInteractor().onProfileImageUploadSuccess(response.body());
}
});
}
答案 5 :(得分:0)
答案 6 :(得分:0)
完全同意@ tir38和@android_griezmann。这将是kotlin中的版本:
interface servicesEndPoint {
@Multipart
@POST("user/updateprofile")
fun updateProfile(@Part("user_id") id:RequestBody, @Part("full_name") other:fullName, @Part image: MultipartBody.Part, @Part("other") other:RequestBody): Single<UploadPhotoResponse>
companion object {
val API_BASE_URL = "YOUR_URL"
fun create(): servicesPhotoEndPoint {
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(API_BASE_URL)
.build()
return retrofit.create(servicesPhotoEndPoint::class.java)
}
}
}
// pass it like this
val file = File(RealPathUtils.getRealPathFromURI_API19(context, uri))
val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
// MultipartBody.Part is used to send also the actual file name
val body: MultipartBody.Part = MultipartBody.Part.createFormData("image", file.name, requestFile)
// add another part within the multipart request
val fullName: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name")
servicesEndPoint.create().updateProfile(id, fullName, body, fullName)
要获取真实路径,请使用RealPathUtils。在以下问题的@Harsh Bhavsar答案中检查此类:How to get the Full file path from URI。
要获取RealPathFromURI_API19,您需要READ_EXTERNAL_STORAGE权限
答案 7 :(得分:0)
Retrofit 2.0解决方案
@Multipart
@POST(APIUtils.UPDATE_PROFILE_IMAGE_URL)
public Call<CommonResponse> requestUpdateImage(@PartMap Map<String, RequestBody> map);
和
Map<String, RequestBody> params = new HashMap<>();
params.put("newProfilePicture" + "\"; filename=\"" + FilenameUtils.getName(file.getAbsolutePath()), RequestBody.create(MediaType.parse("image/jpg"), file));
Call<CommonResponse> call = request.requestUpdateImage(params);
您可以使用
图片/ jpg
图片/ png
图片/ gif