我正在开发一个将图像发送到服务器的应用程序。我想将来自应用程序的照片保存在本地服务器端文件夹中。为此,我使用 SpriingBoot 进行 API 开发,在 Android 上,我使用 Volley 库通过 Json 提交请求。
我已经尝试将请求中的字符串转换为 byte[],然后将其保存为 Image.io 格式的文件,但无法保存图像。有人可以帮我把图片保存到本地服务器目录吗?
安卓代码:
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 的后端实现,您可以使用 Retrofit 以一种漂亮而干净的方式轻松地将图像发送到您的服务器:
添加到构建文件:
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
像这样在您的应用中配置 Retrofit:
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 调用唱简单的接口(interface):
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) {
}
});
关于java - 使用 Android 的 Spring Boot 将图像保存到服务器目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57477731/