Angularjs $http get not working - angularjs

I am trying to access REST web service from angularjs. I am not able to call it successfully.
AngularJs Code
var singleOrderUrl = "/singleOrder/retrieve";
function getSingleOrderDetails(userName,singleOrderUrl,$http,$q) {
var fd = new FormData();
var deffered = $q.defer();
fd.append('USERNAME', 'test123');
//fd.append();
//fd.append();
console.log("inside service"+userName+"singleOrderUrl:::"+singleOrderUrl);
return $http.get(singleOrderUrl, fd, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined,
}
}).success(function(response) {
console.log(response);
responseData = response.data.toString();;
deffered.resolve(response);
return responseData;
}).error(function(error) {
alert("error");
deffered.reject(error);
return "failed";
});
};
Rest Service code
#RestController
public class SingleOrderHistoryController {
private static final Logger logger = LoggerFactory.getLogger(SingleOrderHistoryController.class.getName());
#RequestMapping(value = "/singleOrder/retrieve", method=RequestMethod.GET, produces="application/json")
public List<SingleHistoryRecord> getSingleOrderDetails(#RequestParam(value = Constants.USER_NAME, required = true) String userName, HttpServletRequest request,HttpServletResponse response) throws Exception {
logger.debug("inside SingleOrderHistoryController ");
List<SingleHistoryRecord> singleOrderHistoryList = new ArrayList<SingleHistoryRecord>();
SingleHistoryRecord record1 = new SingleHistoryRecord();
SingleHistoryRecord record2 = new SingleHistoryRecord();
record1.setClientIdentifier(userName);
record1.setSubmitDate("01/05/2017");
record1.setStatus("Complete");
record1.setReferenceID("1234555");
record1.setOrderID("test123");
record2.setClientIdentifier(userName);
record2.setSubmitDate("01/05/2017");
record2.setStatus("Complete");
record2.setReferenceID("1234555");
record2.setOrderID("test123");
singleOrderHistoryList.add(record1);
singleOrderHistoryList.add(record2);
return singleOrderHistoryList;
}
Can anyone please advise what I am doing wrong here, It is getting the source code of the page in response instead of getting the list.

Related

Unable to display upload images from s3 bucket in asp.net mvc

I try to display images from s3 bucket in asp.net mvc I get the base64 encoded response. but is not display image in the view
first image is in binary encoding, rather than Base64.
so I convert into base64 with this
function _arrayBufferToBase64()
This is my view
<img data-ng-src="data:image/jpeg;charset=utf-8;base64,{{str}}"
alt="MyImage">
This is my MVC controller
[HttpGet]
public ActionResult GetReadObject()
{
string responseBody = "";
try
{
using (IAmazonS3 s3client = new AmazonS3Client(_awsAccessKey, _awsSecretKey, RegionEndpoint.USEast1))
{
GetObjectRequest request = new GetObjectRequest
{
BucketName = _bucketName,
Key = keyName
};
using (GetObjectResponse response = s3client.GetObject(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
string title = response.Metadata["x-amz-meta-title"];
Console.WriteLine("The object's title is {0}", title);
responseBody = reader.ReadToEnd();
}
}
}
catch (Exception ex)
{
}
return Json(responseBody, JsonRequestBehavior.AllowGet);
}
This is my controller
app.controller('myCtrl', function ($scope, $http) {
$http({
method: 'GET',
url: '/User/Dashboard/GetReadObject',
responseType: 'arraybuffer'
}).then(function (response) {
alert("1");
console.log(response);
var str = _arrayBufferToBase64(response.data);
$scope.getImage = str;
alert(str);
console.log(str);
// str is base64 encoded.
},
function (response) {
console.error('error in getting static img.');
});
function _arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
})
You should try
<img data-ng-src="data:image/jpeg;charset=utf-8;base64,{{getImage}}"
alt="MyImage">
As you mentioned in your controller, str is simple javascript variable that you could not use with View. As you assign str value to $scope.getImage ($scope.getImage = str) You can use {{getImage}} with angular expression in your View.

Not able to expose the custom headers from WebAPI to client

I have written a program to download the pdf, word or txt file returned by web api and it's working fine. On server side I have used WebApi and client side AngularJs. Now the problem is, I also need the file name from api as well and for that I need to read the headers returned by api. But reponse.headers doesn't contains all the headers info. Below is my code:
[HttpGet]
[Authorize]
public HttpResponseMessage GetTranscript(string key, int format)
{
var badRequest = Request.CreateResponse(HttpStatusCode.OK, "Not a valid input."); //ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, "Not a valid input."));
if (string.IsNullOrWhiteSpace(jiraTaskKey))
{
return badRequest;
}
string transcript = _mediaCaptionService.GetTranscript(UserId, key);
string fileName = "transcript";
var response = new HttpResponseMessage(HttpStatusCode.OK);
if (format == (int)TranscriptFormat.PDF)
{
byte[] byteInfo = GeneratePDFTranscript(transcript);
response.Content = new ByteArrayContent(byteInfo);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
fileName = fileName + ".pdf";
}
else if (format == (int)TranscriptFormat.TXT)
{
response.Content = new StringContent(transcript, System.Text.Encoding.UTF8, "text/plain");
fileName = fileName + ".txt";
}
else if (format == (int)TranscriptFormat.WORD)
{
string transcriptFontName = "Arial";
byte[] byteInfo = GenerateWordTranscript(transcript, transcriptFontName);
response.Content = new ByteArrayContent(byteInfo);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
fileName = fileName + ".doc";
}
else
{
return badRequest;
}
response.Content.Headers.Add("x-filename", fileName);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = fileName
};
//response.Content.Headers.ContentDisposition.FileName = fileName;
return response; //ResponseMessage(response);
}
and in client side
function getTranscriptResult(method, apiUrl, data) {
var deferred = $q.defer();
$http({
method: method,
url: apiUrl,
data: data,
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
debugger;
var results = [];
results.data = data;
results.headers = headers();
results.status = status;
results.config = config;
deferred.resolve(results);
}).error(function (error, status, headers, config) {
deferred.reject(error);
});
return deferred.promise;
}
But when I put the break point in above code, I get this:
Can you please tell me where is the problem in my code that I am not able to get the file name? Also please let me know if you need more information.
After adding below lines has solved my problem.
// Add a custom header for filename and expose it to be consumed by JavaScript.
response.Content.Headers.Add("Filename", zipFileName);
response.Content.Headers.Add("Access-Control-Expose-Headers", "Filename");
So basically adding Access-Control-Expose-Headers helped me to expose the custom headers to client. For more information on this please follow this link

The current request is not a multipart request in angularJS and Spring Rest

I am trying to upload file using AngularJS on client side and Spring RESTApi on server side but getting
Error
org.springframework.web.multipart.MultipartException: The current request is not a multipart request
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.assertIsMultipartRequest(RequestParamMethodArgumentResolver.java:216)
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.resolveName(RequestParamMethodArgumentResolver.java:167)
.......
[http-bio-8080-exec-1] WARN org.springframework.web.servlet.PageNotFound - Request method 'POST' not supported
Rest API
Below is a simple Java Post function:
#RequestMapping(method = RequestMethod.POST)
public String saveFile(
#RequestParam("file") MultipartFile file) {
return "success";
}
In Angular, I am using Resource service to send request.
Chrome Developer Tool output
Request Payload
------WebKitFormBoundarydFRgXclyfPVixdHo
Content-Disposition: form-data; name="file"; filename="Release_Notes.txt"
Content-Type: text/plain
------WebKitFormBoundarydFRgXclyfPVixdHo--
Angular Service
function FileUploadService($resource) {
return $resource('/fileUpload/:id', {}, {
'save' : {
method : 'POST',
transformRequest: function(data, headersGetter) {
var headers = headersGetter();
headers['Content-Type'] = undefined;
if (data == undefined) {
return data;
}
var fd = new FormData();
var createKey = function(_keys_, currentKey) {
var keys = angular.copy(_keys_);
keys.push(currentKey);
var formKey = keys.shift()
if (keys.length) {
formKey += "[" + keys.join("][") + "]"
}
return formKey;
};
var addToFd = function(object, keys) {
angular.forEach(object, function(value, key) {
var formKey = createKey(keys, key);
if (value instanceof File) {
fd.append(formKey, value);
} else if (value instanceof FileList) {
if (value.length == 1) {
fd.append(formKey, value[0]);
} else {
angular.forEach(value, function(file, index) {
fd.append(formKey + '[' + index + ']', file);
});
}
} else if (value && (typeof value == 'object' || typeof value == 'array')) {
var _keys = angular.copy(keys);
_keys.push(key)
addToFd(value, _keys);
} else {
fd.append(formKey, value);
}
});
};
addToFd(data, []);
return fd;
}
}
});
}
Any hint to avoid this error?
Method assertIsMultipartRequest from RequestParamMethodArgumentResolver class is called.
The method asserts that it is a post request and content type starts with multipart/
if (!"post".equals(request.getMethod().toLowerCase())) {
return false;
}
String contentType = request.getContentType();
return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
Your content type, on the other hand, is
Content-Type: text/plain
And an exception is thrown.
#RequestMapping(method = RequestMethod.POST)
your value attribute is missing in the requestmapping it should be like this
#RequestMapping(value="/fileupload/save/{id}" ,method = RequestMethod.POST)
and use this code when creating angular resource
$resource('fileupload/save/:id',
{id:'1'}, {
save: {method:'POST', params:{charge:true}}
});
in springBoot theres not much to configure when uploading the file.
but you can add these properties to your application property file to change the file size limits.
# File size limit
multipart.maxFileSize = 3Mb
# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb
The above issue is resolved by:
1) Creating a MultipartResolver bean in WebAppConfig.java as shown below:
#Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
2) Replacing AngularJS FileUploadService (which is using Resource service) with http as shown below:
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
Hope it helps.

sending HashMap by angularjs $http.get in spring mvc

I want to send and retrieve HashMap through angularjs and receive it in springmvc controller. I have successfully send and received List but unable to send HashMap.
My code is.
$scope.addskill = function(skills){
// $scope.list = [];
// $scope.list.push(skills.skillName, skills.expMonth, skills.expYear, skills.experties);
var map = {};
map['name'] = skills.skillName;
map['month'] = skills.expMonth;
map['year'] = skills.expYear;
map['experties'] = skills.experties;
alert(map['name']);
var response = $http.get('/JobSearch/user/addskill/?map=' +map);
// var response = $http.get('/JobSearch/user/addskill/?list=' +$scope.list);
response.success(function(data, status, headers, config){
$scope.skills = null;
$timeout($scope.refreshskill,1000);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
};
My mvc Controller is :
#RequestMapping(value = "/addskill", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addStudentSkill(#RequestBody HashMap<String,String> map){
System.out.println(map.get("name"));
/*
* public void addStudentSkill(#RequestParam("list") List list){
try{
StudentSkills skills = new StudentSkills();
skills.setSkillName(list[0]);
skills.setExpMonth(Integer.parseInt(list[1]));
skills.setExpYear(Integer.parseInt(list[2]));
skills.setExperties(list[3]);
skills.setStudent(studentService.getStudent(getStudentName()));
studentService.addStudentSkill(skills);
}catch(Exception e){};
*/
}
Commented code works when i send and receive List. I want to use key to retrieve data. If there is any better way please suggest.
The error is cannot convert java.lang.string to hashmap
You're sending the map as a request parameter. And you're trying to read it in the request body. That can't possibly work. And GET requests don't have a body anyway.
Here's how you should do it:
var parameters = {};
parameters.name = skills.skillName;
parameters.month = skills.expMonth;
parameters.year = skills.expYear;
parameters.experties = skills.experties;
var promise = $http.get('/JobSearch/user/addskill', {
params: parameters
});
And in the Spring controller:
#RequestMapping(value = "/addskill", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addStudentSkill(#RequestParam("name") String name,
#RequestParam("name") String month,
#RequestParam("name") String year,
#RequestParam("name") String experties) {
...
}
That said, given the name of the method addStudentSkill, and the fact that it doesn't return anything, it seems this method is not used to get data from the server, but instead to create data on the server. So this method should be mapped to a POST request, and the data should be sent as the body:
var data = {};
data.name = skills.skillName;
data.month = skills.expMonth;
data.year = skills.expYear;
data.experties = skills.experties;
var promise = $http.post('/JobSearch/user/addskill', params);
and in the controller:
#RequestMapping(value = "/addskill", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.CREATED)
public void addStudentSkill(#RequestBody Map<String, String> data) {
...
}

415- Unsupported Media Type Error | angularjs + Spring3.2

I am getting 415 error in browser. I am not able to find the mistake. Could you please help.
loginController.js
$scope.user = {email: "admin", password: "password"};
$http.post('/expense-manager-api/login/authenticate', $scope.user, {
headers: {"Content-Type": "application/json"}
}).success(function(login) {
$scope.setError(login.status);
$location.path("main");
}).error(function() {
$scope.setError('Invalid user/password combination');
});
LoginController.java
#Controller
#RequestMapping("/login")
public class LoginController {
#RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public
#ResponseBody
LoginResponse login(#RequestBody LoginRequest loginRequest) {
if (loginRequest.getEmail().equals("admin") && loginRequest.getPassword().equals("password")) {
UUID uuid = UUID.randomUUID();
return new LoginResponse(uuid.toString(), "OK");
}
return new LoginResponse(null, "Invalid user/password combination");
}
}
Jackson mapper fixed the problem.
add maven dependency of Jackson-mapper in your pom.xml

Resources