简体   繁体   中英

Getting a file with “0 bytes on disk” after uploading it using retrofit2

I'm working in a mobile version of a website I made as my school project, the website itself works fine, my backend seems to work fine as well so I'm using the same PHP files, I'm just building the front-end side.

I'm using Retrofit2 to consume my PHP files and I faced a problem, I can't upload any file properly from the mobile app, the entire database stuff works fine but when it comes to upload the file something goes wrong, the uploaded file has 0 bytes on disk

1.- I get the picture from gallery using an Intent

Intent intent = new Intent();
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Selecciona las imagenes"), PICK_IMAGE_REQUEST );

onActivityRestult:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            File file = new File(getPathFromURI(getContext(), data.getData()));

            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getPathFromURI(getContext(), data.getData()));
            multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);
        }
    }

2.- I call the PHP file

RetrofitInterface retrofitInterface = RetrofitClient.createRetrofit().create(RetrofitInterface.class);
// The first 8 params are for the database stuff, the last param "multipartBody" is the one who doesnt work
    Call<RespuestaGenerica> call = retrofitInterface.crearEvento(idUsuario, nombre, descripcion,
            domicilio, fecha, entrada, ciudad, result, multipartBody);

    call.enqueue(new Callback<RespuestaGenerica>() {
        @Override
        public void onResponse(Call<RespuestaGenerica> call, Response<RespuestaGenerica> response) {
            Log.d(TAG, response.body().toString());
        }

        @Override
        public void onFailure(Call<RespuestaGenerica> call, Throwable t) {
            Toast.makeText(getContext(), "Error al crear el evento: " + t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

The retrofit interface:

@Multipart
@POST("conexiones/contenido/eventos/crearEvento.php")
Call<RespuestaGenerica> crearEvento(@Part("idUsuario")String idUsuario, @Part("nombre")String nombre,
                                    @Part("descripcion")String descripcion, @Part("domicilio")String domicilio,
                                    @Part("fecha")String fecha, @Part("entrada")String entrada,
                                    @Part("ciudad")String ciudad, @Part("tags")String tags,
                                    @Part MultipartBody.Part file);

This is my back-end function to store files

function guardarImagenes ($idEvento) {
    $cont = 0;
    foreach($_FILES as $aux) {
        $ext = 'jpg';
        $nombreFichero = $cont++  . '.' . $ext; // e.j 0.jpg
        $ruta = '../../../media/eventos/'.$idEvento;
        if(!is_dir($ruta)) // Make dir if doesnt exists
            mkdir($ruta);
        $ruta .= '/' . $nombreFichero; // Full route
        move_uploaded_file($aux['tmp_name'], $ruta); // Attempt to upload it
    }
}

I can't figure out why is it uploading a file which has 0 bytes on disk, please help! Thank you c:

The issue could be related to media type used, you could try with:

MediaType.parse(getContentResolver().getType(fileUri))

instead of having MediaType.parse("multipart/form-data" hardcoded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM