Search code examples
androidretrofit2multipart

POSTing an audio file with Retrofit


The problem is this. I am sending a music file. I keep getting error 422. For this reason, it seems I am not able to properly position my body

enter image description here this is my output from the console

Content-Disposition: form-data; name="Content-Disposition: form-data; 
name="audio[file]"; filename="tr.mp3""
Content-Transfer-Encoding: binary
Content-Type: audio/mpeg
Content-Length: 6028060

and my code

@Multipart
@Headers({"Content-Type: multipart/form-data;", "Accept:application/json, text/plain, */*"})
@POST("audios")
Call<SoundResponse> saveSound(@Part ("Content-Disposition: form-data; name=\"audio[file]\"; filename=\"tr.mp3\"") RequestBody file,
                              @Query("auth_token") String authToken);

and called this method

        RequestBody body = RequestBody.create(MediaType.parse("audio/mpeg"), file);

        GeoService.saveSound(body,SoundResponseCallback, getAuthToken());

I also found this stuff
Send file to server via retrofit2 as object

It seems to me that the problem is that the field looks like this "audio [file]"

Thank you for your help


Solution

  • i found the answer to the question.The solution was that the file had to be converted to bytes

     private void sendFile(Uri data) {
        mParent.showProgress();
        MultipartBody.Part file = packFile(view.getContext(), "audio[file]", data);
        GeoService.saveSound(file, SoundResponseCallback, getAuthToken());
    }
    
    @Nullable
    public static MultipartBody.Part packFile(@NonNull Context context, @NonNull String partName, @Nullable Uri fileUri) {
        if (fileUri == null) return null;
        ContentResolver cr = context.getContentResolver();
        String tp = cr.getType(fileUri);
        if (tp == null) {
            tp = "audio";
        }
        try {
            InputStream iStream = context.getContentResolver().openInputStream(fileUri);
            byte[] inputData = getBytes(iStream);
            RequestBody requestFile = RequestBody.create(MediaType.parse(tp), inputData);
            return MultipartBody.Part.createFormData(partName, fileUri.getLastPathSegment(), requestFile);
        } catch (Exception e) {
            return null;
        }
    }
    
    @Nullable
    private static byte[] getBytes(@Nullable InputStream inputStream) throws IOException {
        if (inputStream == null) return null;
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
    
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }