Tôi đã cố gắng triển khai tính năng tải ảnh hồ sơ lên bằng Android Retrofit + SpringMVC. Máy chủ Java không thể trả lời cuộc gọi API Retrofit. đoạn mã liên quan được đưa ra dưới đây:Không thể tải hình ảnh từ Android lên máy chủ java
ApiInterface
@Multipart
@POST("user/profileImage")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part image, @Part("name") RequestBody name);
uploadToServer
public void uploadToServer(){
//Get retrofit client
Retrofit retrofit = ApiClient.getClient();
//Get API interface
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
// Get image parts
MultipartBody.Part imageParts = bitmapToMultipart(imageBitmap);
//Get image name
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "ProfileImage");
//Call image upload API
Call<ResponseBody> call = apiInterface.uploadImage(imageParts,name);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
ResponseBody body = response.body();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
bitmapToMultipart
public MultipartBody.Part bitmapToMultipart(Bitmap imageBitmap){
File file = null;
try {
//create a file to write bitmap data
file = new File(this.getCacheDir(), "imageBitmap");
file.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
}catch(IOException e){
e.printStackTrace();
}
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
return body;
}
Java SpringMVC khiển
@Controller
@RequestMapping("/user")
public class UserController{
@RequestMapping(value = "/profileImage", method = RequestMethod.POST)
public @ResponseBody String imageUploader(@RequestParam("image") MultipartFile image, @RequestBody RequestBody name)throws Exception{
return "";
}
}
Vấn đề là: Yêu cầu thậm chí không đạt đến máy chủ java.
bitmapToMultipart của bạn() nên 'trả lại null; 'trong đó khối catch. Và nơi bạn gọi hàm đó, bạn nên kiểm tra giá trị trả về cho null. Và không tiếp tục nếu nó là null. Vui lòng điều chỉnh mã của bạn. – greenapps
Tiếp tục loại bỏ ByteArrayOutputStream và nén trực tiếp bitmap của bạn thành 'fos'. – greenapps
'file.createNewFile();'. Loại bỏ dòng đó. – greenapps