如何通过改造从android设备上传照片?

问题描述 投票:1回答:1

我有这样的端点:

图像上传:https://api.imgbb.com/1/upload

参数:key(必填):API密钥。image(必填):二进制文件,base64数据或图像的URL。 (最大16MB)name(可选):文件名,如果使用POST上传文件,则会自动检测到该文件名和多部分/表单数据

[我想通过改造从android设备上传照片,所以我尝试了这个:

public class PhotoNetworkClient {

    public static final String KEY_API="my_key";
    private static final String BASE_URL = "https://api.imgbb.com/1/";
    private static Retrofit retrofit;

    public static Retrofit getRetrofitClient(Context context) {
        if (retrofit == null) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
public interface PhotoService {
    @Multipart()
    @POST("/upload")
    Call<ResponseBody> uploadImage(@Query("key") String key, @Part() MultipartBody.Part file );
}

我正在使用这样的东西:

public static void testExecute(Bitmap bitmap, Context context) throws IOException {
    //Convert bitmap to byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 0 /*ignored for PNG*/, bos);
    byte[] bitmapData = bos.toByteArray();
    //create file
    String currentDate = new SimpleDateFormat("ddMMyyyy_HHmmss", Locale.getDefault()).format(new Date());
    File f = new File(context.getCacheDir(), "temp_"+currentDate );
    f.createNewFile();
    FileOutputStream fos = new FileOutputStream(f);
    fos.write(bitmapData);
    fos.flush();
    fos.close();

    Retrofit retrofit = PhotoNetworkClient.getRetrofitClient(context);
    PhotoService uploadAPIs = retrofit.create(PhotoService.class);

    RequestBody requestFile =  RequestBody.create(MediaType.parse("multipart/form-data"), f);
    MultipartBody.Part body = MultipartBody.Part.createFormData("image", f.getName(), requestFile);
    Call call = uploadAPIs.uploadImage(PhotoNetworkClient.KEY_API,body);
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            if (response.isSuccessful())
                Toast.makeText(context, "I send photo", Toast.LENGTH_SHORT);
            else
                Toast.makeText(context, "response isn't successful", Toast.LENGTH_SHORT);
        }
        @Override
        public void onFailure(Call call, Throwable t) {
            Toast.makeText(context, "on failure", Toast.LENGTH_SHORT);
        }
    });
}

});

我收到代码为200的回复,但图像未上传到服务器

java android retrofit image-uploading
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.