アンドロイドでSpringBootを使用して、サーバーのディレクトリに画像を保存します

ネット上の技術:

私は、サーバーに画像を送信するアプリケーションを開発しています。私は、ローカルサーバ側フォルダ内のアプリケーションから写真を保存したいのです。このために私はAPIの開発のためのSpriingBootを使用していますが、Android上で私はバレーのライブラリを使用してJSONを介して要求を提出しています。

私はすでにバイト[]への要求に来て、その後保存Image.io形式のファイルに文字列を変換しようとしたが、画像を保存することはできません。誰かの助けが私には、ローカルサーバのディレクトリに画像を保存することはできますか?

コードは、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);
}
}

コードAPI:

サービス:

@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;
}

これは、画像属性がnullであることを、コードに戻ったようです

スタッカー:

NONAMEのバックエンドの実装@使用して簡単に使用してサーバーに画像を送信することができますレトロフィットをきれいな方法で:

ビルドファイルに追加します。

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

このようなあなたのアプリ内で設定をレトロフィット:

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;
}

}

API呼び出しが簡単なインターフェースを歌うあなたを定義します。

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

}

最後に、このように上記の構成を使用して画像を送信します。

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) {
     }
 });

}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=315382&siteId=1