Why the String inside Controller not printing anything? - java

I am trying to send Image and Id using retrofit for that i am sending Multipart file and String.
This is my Upload Method on Android side ->
private void UploadFiles() {
File uploadFile = fileArrayList.get(0);
if (uploadFile != null) {
Log.d(TAG, "UploadFiles: File Name is -> " + uploadFile.getName());
// Parsing any Media type file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part cropImage = MultipartBody.Part.createFormData("cropImage", uploadFile.getName(), requestFile);
RequestBody cropId = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile.getParentFile().getName());
Api.uploadCropImage(cropImage,cropId, new Callback<BasicResponse>() {
#Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
if (response.body() != null) {
Log.d(TAG, "onResponse: Success" + response.body().getResponse());
}
else{
Log.d(TAG, "onResponse: null Response");
}
}
#Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
Log.d(TAG, "onResponse: Failure");
}
});
}
}
My Upload CropImage Method ->
public static void uploadCropImage(MultipartBody.Part multipartBody,RequestBody cropId,
Callback<BasicResponse> callback) {
UploadCropImageApi uploadCropImageApi = retrofit.create(UploadCropImageApi.class);
Call<BasicResponse> call = uploadCropImageApi.uploadCropImage(multipartBody,cropId);
call.enqueue(callback);
}
My Interface ->
public interface UploadCropImageApi {
#Multipart
#POST(UPLOAD_FILE_TO_AWS_URL)
Call<BasicResponse> uploadCropImage(#Part MultipartBody.Part cropImage, #Part("cropId") RequestBody cropId);
}
This is my Spring Controller, What's wrong with it? It's not printing cropId.
#RequestMapping(value = "/UploadCropImage", method = RequestMethod.POST, consumes = {"multipart/form-data"})
#ResponseBody
public String UploadImage(#RequestBody MultipartFile cropImage,#RequestBody String cropId ,HttpServletRequest request) {
System.out.println("String is -> " + cropId);
return null;
}

You cannot use two #RequestBody as it can bind to a single object only (the body can be consumed only once)
You need to use #RequestParam String cropId instead of RequestBody.
See here for clarification
UPDATE :Here is your controller method look like
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(#RequestParam("name") String name, #RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location=" + serverFile.getAbsolutePath());
return null;
} catch (Exception e) {
return null;
}
}
}

Related

How to upload a file from Android to Java Web Service?

I'm trying to send a file from android to my webserver through a Rest API, but I don't know how to handle the MultipartBody.Part object in java.
API Request:
#Multipart
#POST("utilizadores/upload")
Call<ResponseBody> uploadPhoto(
#Part MultipartBody.Part fotografia);
Android Code:
File file = new File(getPath(data));
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part parts = MultipartBody.Part.createFormData("images", file.getName(), requestBody);
Call<ResponseBody> call = RetrofitClient
.getInstance()
.getApi()
.uploadPhoto(parts);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(getContext(), response.message(), Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
Java Code:
What should I pass as parameter in the next function 'uploadFile()'?
The value of fotografia is '(NULL)'.
#POST
#Path("/upload")
#Produces(MediaType.APPLICATION_JSON)
public Response uploadFile(#QueryParam("fotografia") String fotografia) {
BD bd = new BD();
int id = 54;
try {
String path = "/fotografias/" + id + ".jpg";
//guardarFicheiro(fotografia, path);
ConnectionBD connection = bd.abrirLigacao();
PreparedStatement ps = connection.getConn()
.prepareStatement("UPDATE utilizador SET fotografia=? WHERE id=?");
ps.setString(1, fotografia);
ps.setInt(2, id);
int x = ps.executeUpdate();
if (x > 0) {
bd.fecharConexao(connection);
return Response.ok().build();
}
bd.fecharConexao(connection);
} catch (SQLException ex) {
System.out.println(ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}

Need to get a string from response returned by api using retrofit2

I am trying to get string value returned by API on success. I am getting success but I do not getting the required value in the response, but when I navigate to response-> body-> responseBody then it shows me that value but I am unable to get that value (please check screen shot for detail).
private void uploadImage(String imagePath) {
try{
showProgressDialogue();
File file = new File(imagePath);
RequestBody photoContent = RequestBody.create(MediaType.parse("multipart/form data"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("file",file.getName(),photoContent);
//RequestBody description = RequestBody.create(MediaType.parse("description"),"abc");
UploadService uploadService = APIClient.getClient().create(UploadService.class);
Call call1 = uploadService.UploadOMRExamPaper(photo);
call1.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, Response<Response> response) {
progressBar.dismiss();
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
progressBar.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}catch (Exception e){
progressBar.dismiss();
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
}
Change your code:
From:
File file = new File(imagePath);
RequestBody photoContent = RequestBody.create(MediaType.parse("multipart/form data"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("file",file.getName(),photoContent);
To:
File file = new File(imagePath);
RequestBody photoContent = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("upload", file.getName(), photoContent );
Note:"upload" is just example here,you should write there from your api paramater.

video streaming is very slow in java spring MVC

#RequestMapping(value = "/video/{clientID}/{fileName}", method = RequestMethod.GET)
public ResponseEntity<StreamingResponseBody> getClientVideo(#PathVariable(value = "clientID") Integer clientID, #PathVariable(value = "fileName") final String fileName) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String absolutePath = new File(".").getAbsolutePath();
File file = new File(Paths.get(absolutePath).getParent() + "/" + clientID);
if (null != file) {
FilenameFilter beginswithm = new FilenameFilter() {
public boolean accept(File directory, String filename) {
return filename.contains("ClientVideo_"+fileName);
}
};
File[] files = file.listFiles(beginswithm);
if (null != files && files.length > 0) {
Resource resource = null;
for (final File f : files) {
headers.set("Content-Disposition", "inline; filename=" + f.getName());
StreamingResponseBody responseBody = new StreamingResponseBody() {
#Override
public void writeTo(OutputStream out) throws IOException {
out.write(Files.readAllBytes(f.toPath()));
out.flush();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(responseBody); //(responseBody, headers, HttpStatus.OK);
}
}
}
RecruiterResponseBean resBean = new RecruiterResponseBean();
resBean.setStatusMessage("Video is not present : " + Constants.FAILED);
resBean.setStatusCode(Constants.FAILED_CODE);
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
video streaming is working but it is very slow. how to increase the efficiency?
There is no problem with internet it is 10mbps. i am using tomcat 7 and Spring MVC[4.2.4]. should I change the tomcat capacity or how it can be solve? i am not getting in google.

Uploading image by using Retrofit

I've been trying to upload an image from my application through API. But I keep getting this as response:
{"error":"<p>You did not select a file to upload.<\/p>"}
This is my code:
APIService.java
#Multipart
#POST("/media/upload.html")
Call<UploadImg> uploadimage (#Part MultipartBody.Part file);
UploadImageActivity.java
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
Picasso.with(this).load(uri).fit().into(btn_img_picker);
String imagePath;
if (data.toString().contains("content:")) {
imagePath = getRealPathFromURI(uri);
} else if (data.toString().contains("file:")) {
imagePath = uri.getPath();
} else {
imagePath = null;
}
File file = new File(imagePath);
System.out.println(imagePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);
System.out.println(file.getName());
Call<UploadImg> call = mAPIService.uploadimage(body);
call.enqueue(new Callback<UploadImg>() {
#Override
public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
System.out.println(response.raw());
}
#Override
public void onFailure(Call<UploadImg> call, Throwable t) {
System.out.println(t);
}
});
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = getContentResolver().query(contentUri, proj, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
I have tested sending image in Postman's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.
Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:
/storage/emulated/0/Download/download.jpg
If this is the incorrect path to send, please tell the correct one. Thanks in advance.
try this
#Multipart #POST("user/updateprofile") Observable<ResponseBody>
updateProfile(#Part("user_id") RequestBody id, #Part("full_name")
RequestBody fullName, #Part MultipartBody.Part image, #Part("other")
RequestBody other);
pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg"); RequestBody
requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
add another part within the multipart request
RequestBody fullName = RequestBody.create( MediaType.parse("multipart/form-data"), "Your Name");
service.updateProfile(id, fullName, body, other)
You can use below code for uploading image
First you write code for calling request
//profile pic is image path
RequestBody imagePath = Utility.imageToBody(profilePic);
TestApiInterface service = WebServiceCaller.getClient();
Call<SuccessResponse> call = service.mediaUpload(imagePath);
call.enqueue(new Callback<SuccessResponse>() {
#Override
public void onResponse(Call<SuccessResponse> call,
Response<SuccessResponse> response) {
SuccessResponse result;
if (response.isSuccessful()) {
result = response.body();
}
}
#Override
public void onFailure(Call<SuccessResponse> call, Throwable t) {
}
});
Then you write code for API
#Multipart
#POST("user/mediaupload")
Call<SuccessResponse> mediaUpload(#Part("media_file\"; filename=\"test_media.png\" ") RequestBody media_file);
Then code for Imagetobody covert is below
public static RequestBody imageToBody(String text) {
RequestBody requestBody;
if (text != null && text.length() > 0) {
MediaType MEDIA_TYPE = MediaType.parse("image/*");
File file = new File(text);
requestBody = RequestBody.create(MEDIA_TYPE, file);
} else {
requestBody = null;
}
return requestBody;
}
Try this I had another way to implement
Inside your interface
#Multipart
#POST("edit_profile")
Call<TokenResponse> getTokenAccess(#PartMap Map<String, RequestBody> map);
Call in your Activity
private void getData() {
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("your_base_url_here")
.addConverterFactory(GsonConverterFactory.create())
.build();
Click service=retrofit.create(Click.class);
File file = new File("/storage/sdcard0/Pictures/OGQ/Puskinn Sharma_Jump roof skyscraper_YkRiRWpYcw.jpg");
//make sure your image path is valid
String convert_File_2String= String.valueOf(file);
String fileNAme=convert_File_2String.substring(convert_File_2String.lastIndexOf("/")+1);
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "Sunil");
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "56");
RequestBody lastname= RequestBody.create(MediaType.parse("text/plain"), "Kumar");
Map<String, RequestBody> map = new HashMap<>();
map.put("profile_pic\"; filename=\""+fileNAme+"\" ", fbody);
map.put("firstname", name);
map.put("user_id", id);
map.put("lastname",lastname);
Call<TokenResponse> tokenResponseCall=service.getTokenAccess(map);
tokenResponseCall.enqueue(new Callback<TokenResponse>() {
#Override
public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
TokenResponse tokenResponse=response.body();
Log.e("93","MA>>"+tokenResponse.getJwt());
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<TokenResponse> call, Throwable throwable) {
Log.e("172","><<>>"+throwable);
Log.e("TAG", "onFailure: 173"+call.toString() );
}
});
}

why java streaming video is not playing in crome browser but is playing in firefox

#RequestMapping(value = "/video/{clientID}/{fileName}", method = RequestMethod.GET)
public ResponseEntity<StreamingResponseBody> getClientVideo(#PathVariable(value = "clientID") Integer clientID, #PathVariable(value = "fileName") final String fileName) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String absolutePath = new File(".").getAbsolutePath();
File file = new File(Paths.get(absolutePath).getParent() + "/" + clientID);
if (null != file) {
FilenameFilter beginswithm = new FilenameFilter() {
public boolean accept(File directory, String filename) {
return filename.contains("ClientVideo_"+fileName);
}
};
File[] files = file.listFiles(beginswithm);
if (null != files && files.length > 0) {
Resource resource = null;
for (final File f : files) {
headers.set("Content-Disposition", "inline; filename=" + f.getName());
StreamingResponseBody responseBody = new StreamingResponseBody() {
#Override
public void writeTo(OutputStream out) throws IOException {
out.write(Files.readAllBytes(f.toPath()));
out.flush();
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return ResponseEntity.ok().headers(headers).contentType(MediaType.APPLICATION_OCTET_STREAM).body(responseBody); //(responseBody, headers, HttpStatus.OK);
}
}
}
RecruiterResponseBean resBean = new RecruiterResponseBean();
resBean.setStatusMessage("Video is not present : " + Constants.FAILED);
resBean.setStatusCode(Constants.FAILED_CODE);
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
I am using Spring MVC, I tried many methods but all are downloading the video. Above code is streaming the video, the problem is: in firefox it is streaming but in crome it is downloading. I want to play streaming video in crome also like below ex.
[Ex streaming video: http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4]
Do I need to add more Headers? [if so, which headers need to add?]
Or Did i miss anything?

Categories