not able to upload image to java restful web service - angularjs

My angular controller is
app1.controller('kyc_controller', ['$scope', '$http', function($scope, $http)
{
$scope.uploadFile = function(){
var file = $scope.myFile;
var fd = new FormData();
fd.append('file', file);
$http({
method : 'POST',
url: '/GngService/api/GoNoGo/upload_file',
params : {'filename':'pancard'},
data : fd,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + JSON.stringify(data));
});
};
}]);
and my server side api method is
#POST
#Path("/upload_file")
#Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED})
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response upload(#FormDataParam("file") InputStream ins, #FormDataParam("filename") String filename, #FormDataParam("file") FormDataContentDisposition contentDispositionHeader ) throws IOException {
System.out.println(filename);
BufferedImage image = ImageIO.read(ins);
// ImageIO.write(image, "jpg", new File("/../../fileName"));
String result = "{'status' : 'ok'}";
String json = new Gson().toJson(result);
return Response.ok(json.toString(), MediaType.APPLICATION_JSON).build();
}
It shows Unsupported media type...please help me to upload images....thanks in advance

Related

file not binding to angularjs service using FormData

I am trying to upload a file using angularjs and spring 3, I have written a service which is not binding the selected file. I don't know what mistake I have been doing, please help me to solve this problem. I am using commonsmultipart for uploading the files. following are the fileUploadService and controller codes.
MyApp.service('fileUploadService', function ($http, $q) {
this.uploadFileToUrl = function (file, uploadUrl, formData) {
//FormData, object of key/value pair for form fields and values
var fileFormData = new FormData();
fileFormData.append('fileUpload', file);
// console.log(formData);
fileFormData.append('name', formData.name);
fileFormData.append('email', formData.email);
fileFormData.append('password', formData.password);
fileFormData.append('mobile_no', formData.mobile_no);
fileFormData.append('register-submit', 'Register Now');
var deffered = $q.defer();
$http.post(uploadUrl, fileFormData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (response) {
deffered.resolve(response);
}).error(function (response) {
deffered.reject(response);
});
return deffered.promise;
}
});
Spring Controller:
#SuppressWarnings({ "unused", "static-access" })
#RequestMapping( value="/RegisterCandidate" , method = RequestMethod.POST)
private String RegisterCandidate(HttpServletRequest request,
HttpServletResponse response,
#RequestParam CommonsMultipartFile[] fileUpload ) throws Exception{
System.out.println("In method");
String email = request.getParameter("email");
System.out.println("email==============="+email);
String Password = request.getParameter("password");
String usr_name = request.getParameter("name");
String mobile_no = request.getParameter("mobile_no");
Date dateentry = new Date();
java.sql.Timestamp entry_date = new Timestamp(dateentry.getTime());
Users_Pojo usr = new Users_Pojo();
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload){
usr.setFilename(aFile.getOriginalFilename());
usr.setFile_data(aFile.getBytes());
System.out.println("aFile.getBytes()======"+aFile.getBytes());
System.out.println("aFile.getInputStream()======"+aFile.getInputStream());
System.out.println("aFile.getStorageDescription()======"+aFile.getStorageDescription());
System.out.println("aFile.getSize();======"+aFile.getSize());
System.out.println("aFile.getContentType();==="+aFile.getContentType());/* */
}
}
MD5CodeGenerator md5 = new MD5CodeGenerator();
usr.setUc_password(md5.convertToMD5(Password));
usr.setUc_name(email);
usr.setUc_contact_person(email);
usr.setUc_phone_no(BigInteger.valueOf(Long.parseLong(mobile_no)));
usr.setUc_email_id(email);
usr.setUc_type_id(1);
usr.setUc_active(1);
usr.setValid_from(null);
usr.setValid_to(null);
usr.setDesignation("jobseekar");
usr.setIp_address("164.100.19.79");
usr.setUser_location(1);
usr.setEntry_date(entry_date);
scm_service.save(usr, email);
return "success";
}

How to Download binary file in angular js using http

I want to downlaod exe file using $http, it shows me when I console the data, but I am unable to download it.
$http({
url: url,
method: "GET",
headers: {
'Content-type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log(data);
window.open(objectUrl);
}).error(function (data, status, headers, config) {
//upload failed
});
Any help would be appreciated.
you can Use response type like responseType: "arraybuffer"
$http({
url: url,
method: "GET",
headers: {
'Content-type': 'application/json'
},
responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
console.log(data);
var file = new Blob([data], { type: 'application/binary' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
var link=document.createElement('a');
link.href=fileURL;
link.download="testing.exe";
link.click();
window.open(objectUrl);
}).error(function (data, status, headers, config) {
//upload failed
});
and use Blob and pass type "application/binary" and create a link to download it.
Given code will help you to download exe file as well as to check
browser compatibility.
var ieEDGE = navigator.userAgent.match(/Edge/g);
var ie = navigator.userAgent.match(/.NET/g); // IE 11+
var oldIE = navigator.userAgent.match(/MSIE/g);
var blob = new window.Blob([data.data], { type: 'application/x-msdownload' });
if (ie || oldIE || ieEDGE) {
var fileName="filename"+'.exe';
window.navigator.msSaveBlob(blob, fileName);
}
else {
var file = new Blob([ data.data ], {
type : 'application/x-msdownload'
});
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = "filename"+'.exe';
document.body.appendChild(a);
a.click();
}
//Successfully Downloaded

AngularJS + Jersey POST Bad Request

I have following API in jersey for file upload :
#Path("/image/upload")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("application/json")
public Response Imageupload(
#QueryParam("filename") String filename,
#FormDataParam("file") InputStream fileInputString,
#Context ContainerRequestContext crc)
throws ConnectException, SQLException, InvalidCredentialsException, IOException, GeneralException {
}
and I am using angular js for uploading file :
_myApp.service('fileUpload', ['$rootScope', '$http', function($rootScope, $http) {
this.uploadFileToUrl = function(file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + $rootScope.token
},
params:{
'filename':file.name
}
})
.success(function() {
})
.error(function() {
});
}
}]);
_myApp.controller('uploadImageController', ['$rootScope', '$scope', '$http', 'fileUpload', function($rootScope, $scope, $http, fileUpload) {
$rootScope.show = true;
$scope.upload = function() {
//$scope.fileObject is the File I am trying to upload
console.log($scope.fileObject);
var file = $scope.fileObject;
var uploadUrl = "http://xx.xx.xx.xx:8080/ImageAPIS/image/upload";
fileUpload.uploadFileToUrl(file, uploadUrl);
}
I am getting the following error :
400 Bad request : The request sent by the client was syntactically incorrect.
Am I posting the request in wrong Angular standard? I can see the payload being sent, What mismatch is between the Jersey and my Angular request sent?
I have refereed the following File upload code -http://www.tutorialspoint.com/angularjs/angularjs_upload_file.htm

Unable to get JSON from asmx Web Service in AngularJS

I am unable to parse a json file from a asmx webservice.
Here is my WebMethod:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetDataJSON()
{
//var dt = GetCubeResult("");
var _DbConn = Helper.GetDBConnection();
var _CubeConn = Helper.GetCubeConnection();
var _query = Helper.GetWebConfig("dashboard_config");
Data[] datArray = new Data[1];
Data data = GetTilesAsDataArray(_query, _DbConn);
datArray[0] = data;
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
/*
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type,Accept,Origin,X-Requested-With");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
*/
Context.Response.Write(serializer.Serialize(datArray));
}
and here is my AngularJS Code
app.controller('jsonServerBox', ['$scope', '$http', function($scope, $http) {
$http({
method: 'POST',
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: 'myasmx.asmx/getjson',
data: '[]',
dataType: 'json',
xhrFields: {
withCredentials: true
},
cache: 'false',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
//url: 'serverbox.json'
}).success(function (data) {
//var myjson = JSON.parse(data);
//$scope.ocw = myjson;
//$scope.ocw = JSON.parse(data);
$scope.ocw = data;
$scope.loading = false;
})
.error(function(data, status) {
console.error('Repos error', status, data);
//alert("schlecht");
});}]);
I already try it with parse and other methods, but no one is working - is there any error in my webservice ? with a local json file the angular code is working.
EDIT: Its working now. I changed my angular Code to following:
app.controller('jsonServerBox', ['$scope', '$http', function($scope, $http) {
$http.get("myasmx.asmx/get",
{
params: {
format: "json",
cache: "false"
}
})
.success(function(data){
$scope.ocw = data;
console.log($scope.ocw);
});}]);
But sometimes the browser show it, sometimes not - why is that ? And in IE10 it is not working - no support in ie 10 ?

How to make Spring REST service to accept multipart file data sent by the Angular Controller?

I'm trying to post a file from Angular controller to the backend. But Spring REST controller is receiving null.
JS
myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){
$scope.uploadFile = function(){
var formData=new FormData();
formData.append("file", $scope.myFile);
alert("Hi");
$http({
method: 'POST',
url: 'upload',
headers: {'Content-Type': undefined},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
}).success(function(data, status) {
console.log('file is ' );
console.dir(data);
})
.error(function(data, status) {
});
}
}]);
Spring-REST Controller
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String upload(#RequestBody MultipartFile file) {
System.out.println(file);
}
I also tried with public #ResponseBody void uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) but it's of no use. I have declared multipartResolver in the configuaration file too. Any Idea on this? I'm desperately looking for a solution.
Here is a piece of code that works for me:
Spring-REST Controller
#RequestMapping(value = "/api/users/{id}/image", method = RequestMethod.POST)
#ResponseBody
public boolean uploadUserImage( #PathVariable("id") Long id, #RequestParam("file") MultipartFile file ) {
return userService.saveUserImage(id, file);
}
and on the front-end you could do something like this
Angular Controller
//the image
$scope.uploadme;
$scope.uploadImage = function() {
var fd = new FormData();
var imgBlob = dataURItoBlob($scope.uploadme);
fd.append('file', imgBlob);
$http.post(
'/upload',
fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
)
.success(function(response) {
console.log('success', response);
})
.error(function(response) {
console.log('error', response);
});
}
//you need this function to convert the dataURI
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {
type: mimeString
});
}
Assuming that the http request is correct the problem must be at the Spring controller. I think you have to change upload(#RequestBody MultipartFile file) to upload(#RequestParam("file") MultipartFile file). So it will be like this:
#RequestMapping(value="/upload", method=RequestMethod.POST)
#ResponseBody
public void upload(#RequestParam("file") MultipartFile file) {
System.out.println(file);
}
Also in your function you have it return String but you are not returning one. So i assume you are doing something else and you removed the code in order to post the question and missed the return, otherwise it wouldn't even build.
Lastly you could check this answer that i gave to a similar problem.

Resources