Guardar la imagen en el directorio de servidor utilizando SpringBoot con Android

Tecnología en la Red:

Estoy desarrollando una aplicación que envía imágenes al servidor. Estoy queriendo guardar las fotos procedentes de la aplicación en la carpeta del lado del servidor local. Para ello estoy usando SpriingBoot para el desarrollo de la API y en Android que estoy presentando la solicitud a través de JSON utilizando la biblioteca del voleo.

Ya he intentado convertir la cadena que viene en la solicitud de byte [] y luego guardarlo en un archivo de formato Image.io, pero no es posible guardar la imagen. Puede alguien ayudarme a guardar la imagen en el directorio del servidor local?

Código Android:

public class MainActivity extends AppCompatActivity {

public static final String REGISTER_URL = "http://192.168.1.8:8080/api/paciente";
public static final String KEY_IMAGE = "foto";
String foto = "null";
public static final String TAG = "LOG";
private ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button enviar = (Button) findViewById(R.id.enviar);


    enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            registerForms();

        }
    });
}

public void tirarFoto(View view) {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data != null) {
        Bundle bundle = data.getExtras();
        if (bundle != null) {
            Bitmap img = (Bitmap) bundle.get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            img.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            foto = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
            Toast toast = Toast.makeText(getApplicationContext(), "Foto anexada", Toast.LENGTH_LONG);
            toast.show();
        }
    }
}


@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

public void registerForms() {

    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            if (response.contains("Erro")) {
                //progressDialog.dismiss();
                Toast.makeText(MainActivity.this, "Erro ao enviar", Toast.LENGTH_LONG).show();
                Log.i(TAG, "Lat: " + "Caiu aqui");
            } else {
                //progressDialog.dismiss();
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                Toast.makeText(MainActivity.this, "Enviado com sucesso!", Toast.LENGTH_LONG).show();
                startActivity(intent);
            }

        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                  //progressDialog.dismiss();
                    Toast.makeText(MainActivity.this, "Enviado com sucesso!", Toast.LENGTH_LONG).show();
                    Log.i(TAG, "String: " + foto);
                }
            }) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError{
            Map<String, String> map = new HashMap<String, String>();
            map.put(KEY_IMAGE, foto);
            Log.i(TAG, "Lat: " + map);
            return map;

        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}
}

Código API:

Servicio:

@RequestMapping(value = "/paciente", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = {
        MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE, "application/json" })
public @ResponseBody Paciente cadastraPaciente(@Valid Paciente paciente) throws Exception {
    byte[] imgBytes = Base64.decodeBase64(foto.getBytes());
    try{
        FileOutputStream fos = new FileOutputStream("C:/Users/carlo/Downloads/SisCAF/images/myImage1.png");
         fos.write(imgBytes);
         FileDescriptor fd = fos.getFD();
         fos.flush();
         fd.sync();
         fos.close(); 
     }


    return paciente;
}

Como lo es en el código, los rendimientos que el atributo de imagen es nula

apiladora:

mediante el uso de @ aplicación de back-end de noname puede enviar imágenes a su servidor a través de reequipamiento en un agradable y limpio manera:

añadir a fichero de construcción:

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Configurar reequipamiento dentro de su aplicación como esta:

public class NetworkClient {
private static final String BASE_URL = "http://localhost:8080";
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;
}

}

definiría llamadas a la API cantar interfaces simples:

public interface UploadAPIs {
@Multipart
@POST("/upload")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part file, @Part("name") RequestBody requestBody);

}

Por último, envían sus imágenes utilizando la configuración anterior de esta manera:

private void uploadToServer(String filePath) {
 Retrofit retrofit = NetworkClient.getRetrofitClient(this);
 UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);
 //Create a file object using file path
 File file = new File(filePath);
 // Create a request body with file and image media type
 RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);
 // Create MultipartBody.Part using file request-body,file name and part name 
 MultipartBody.Part part = MultipartBody.Part.createFormData("upload", file.getName(), fileReqBody);
 //Create request body with text description and text media type
 RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");
 // 
 Call call = uploadAPIs.uploadImage(part, description);
 call.enqueue(new Callback() {
     @Override
     public void onResponse(Call call, Response response) {
     }
     @Override
     public void onFailure(Call call, Throwable t) {
     }
 });

}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=315385&siteId=1
Recomendado
Clasificación