Spring get request file not being downloaded - angularjs

I want to download a file when clicking on a button in my AngularJS app which runs on Tomcat with a Java Spring backend but nothing is happening. The method in the backend is called and everything seems to have worked....but my browser doesn't download anything.
What am I missing?
Here's the AngularJS code, which logs Export-Response:[object Object]:
exportProjects() {
let filteredProjectIds = [];
for (let i in this.filteredProjects) {
for (let x = 0, l = this.filteredProjects[i].length; x < l; x++) {
if (!this.isOldProjectsBundle(this.filteredProjects[i][x])) {
filteredProjectIds.push(this.filteredProjects[i][x].id);
}
}
}
this.$http.get('/profiles/projectWordExport?filteredProjects=' + filteredProjectIds.join(",")).then(response => {
console.log("Export-Response:" + response);
return response;
});
}
This is the Java code being called (it's really being called, already debugged it, no errors occuring):
#RequestMapping(value = "/projectWordExport", method = RequestMethod.GET)
public void getProjectsWord(HttpServletRequest request, HttpServletResponse response, #RequestParam String filteredProjects) throws Exception {
//Load project objects from input string or load all projects if input empty
List<Project> projects = new java.util.ArrayList<>();
if (filteredProjects.isEmpty()) {
projects = projectRepository.findAll();
} else {
String[] pIds = filteredProjects.split(",");
for (String pId : pIds) {
projects.add(projectRepository.findById(Long.parseLong(pId)));
}
}
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader("Content-disposition", "attachment;filename=Projektexport.docx");
try {
SaveToZipFile saver = new SaveToZipFile(printer.printProjects(this.prepareProjectExport(projects)));
saver.save(response.getOutputStream());
response.flushBuffer();
} catch (NullPointerException e) {
response.setStatus(500);
response.sendError(500, "Fehler beim exportieren des Tests aufgetreten");
}
}

Put this in #RequestMapping annotation
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE

Related

Decompress byte array in node js

We currently have a project in android and company wants to do some parts on server. Server side code in with Node JS. The thing I want to do looks very simple but I am stuck on that.
We have a long byte array which is compressed, in the android project I have his code that works fine and decompress the byte array. I want to do same in Node JS but I got the error incorrect data check.
public byte[] decompressBytes(byte[] compressedBytes) {
try {
Inflater decompresser = new Inflater();
decompresser.setInput(compressedBytes);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[2048];
while(!decompresser.finished()) {
int cnt = decompresser.inflate(buf);
if(cnt <= 0) {
break;
}
bos.write(buf, 0, cnt);
}
bos.close();
return bos.toByteArray();
} catch (Exception var6) {
return new byte[0];
}
}
Here is the code I wrote form the documents of Pako but as I told it returns error.
function decompress(data, callback) {
var response = '';
var pako = require('pako');
try {
response = pako.inflate(actData);
console.log("response : " + response);
callback('', response);
} catch (err) {
console.log(err);
callback(err, '');
}
}
The inputs are exactly same byte array.
Any help would be appreciated.

How to return data from Web Api controller?

Hi I am developing restfull web api application. After inserting data into database i want to return 0 for success,1 for error and data as unique id assigned to the user. I want to return above data in json format. My requirement is i have to send data to controller in json format and receive data in json format. I have following code and it is working but i want to ask few points here.
Below is my User_Creation controller code.
public result Post(Noor_Users users)
{
result obj = new result();
if (ModelState.IsValid)
{
entityObject.Noor_Users.Add(users);
int result = entityObject.SaveChanges();
if(result==1)
{
obj.success = 0;
obj.id = 5;
return obj;
}
else
{
obj.error = 1;
return obj;
}
}
else
{
obj.error = 1;
return obj;
}
}
}
My service.js file contains below code.
app.service("UserCreation", function ($http) {
this.saveSubscriber = function (sub) {
return $http({
method: 'post',
data: JSON.stringify(sub),
url: 'api/User_Creation',
contentType: "application/json"
});
}
});
This is my controller.js code.
app.controller('UserCreation', function ($scope, UserCreation) {
$scope.saveSubs = function () {
var sub = {
user_email: $scope.user_email,
user_password: $scope.user_password,
};
var saveSubs = UserCreation.saveSubscriber(sub);
saveSubs.then(function (data) {
alert(JSON.stringify(data.data));
}, function (error) {
console.log('Oops! Something went wrong while saving the data.')
})
};
});
I am expecting response in json format as below.
● status - 0 for success, 1 for failure.
● data
○ id - unique id assigned to the user
● error - error message if failed
This is working absolutelt fine. I have below line of code in webapiconfig.cs file
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
With this line of code always i can receive data in json format. But in angularjs success call i need to stringify recieved data. If all my data is returning in json then again why i should convert it to json? Also someone can tell me is above logic is a good practice to return data? Thank you.
Try the following steps:
Add this two line of code on top of your WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
Edit you controller action with following one
public IHttpActionResult Post(Noor_Users users)
{
result obj = new result();
if (ModelState.IsValid)
{
entityObject.Noor_Users.Add(users);
int result = entityObject.SaveChanges();
if (result == 1)
{
obj.success = 0;
obj.id = 5;
}
else
{
obj.error = 1;
}
}
else
{
obj.error = 1;
}
return Ok(obj);
}

Get an image of a vbhtml view as a byte array and save it to an oracle database

I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.

ResponseEnity with angular js

Controller code of Angular Js...
FactoryPBD.showPbdCostCompareData(data).success(
function(result) {
if(result != ""){
//doing my processing and working fine
}).error(function(result,status,message){
console.log("result" , result);
//getting undefined in all the above variable
});
Service code:
showPbdCostCompareData : function(filter) {
promise = $http({
url : 'pbd/showPbdCostCompareData?serachFilterJson='+JSON.stringify(filter),
method : "POST"
});
return promise;
}
Java Controller:-
#RequestMapping(value = "/showPbdCostCompareData", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<String> showPbdCostCompareData(HttpServletRequest request,
#RequestParam String serachFilterJson) {
try {
if (null != serachFilterJson && !"".equalsIgnoreCase(serachFilterJson)) {
Gson gson = new Gson();
SearchCriteriaBean searchCriteriaObj = gson.fromJson(serachFilterJson, SearchCriteriaBean.class);
CnHeaderBean cnHeaderBean = pbdServiceImpl.getPbdCostCompareCnHeaderData(searchCriteriaObj); //getting the value from sevice
List<PbdCostCompareBean> pbdCostCompareList = null;
if (null != cnHeaderBean) {
if("F".equalsIgnoreCase(cnHeaderBean.getPbdType())){
searchCriteriaObj.setFromPartIscb(cnHeaderBean.getFromPartIscb());
searchCriteriaObj.setToPartIscb(cnHeaderBean.getToPartIscb());
pbdCostCompareList = pbdServiceImpl.getPbdCostComparisonData(searchCriteriaObj); //getting the value from sevice
}else{
return new ResponseEntity<String>("Incorrect PBD Type",HttpStatus.SERVICE_UNAVAILABLE);
}
} else {
return new ResponseEntity<String>(HttpStatus.SERVICE_UNAVAILABLE);
}
HashMap<Integer, Object> costCompareMap = new HashMap<Integer, Object>();
costCompareMap.put(1, cnHeaderBean);
costCompareMap.put(2, pbdCostCompareList);
costCompareMap.put(3, pbdServiceImpl.validateUserAccess(searchCriteriaObj, serviceUtility.getUserFromSession(request)));
String pbdDataJsonResponse = gson.toJson(costCompareMap);
return new ResponseEntity<String>(pbdDataJsonResponse, HttpStatus.OK);
} else {
return new ResponseEntity<String>(HttpStatus.SERVICE_UNAVAILABLE);
}
} catch (C2PCException e) {
return new ResponseEntity<String>(e.getMessage(),HttpStatus.SERVICE_UNAVAILABLE);
}
}
I am using Spring Rest controller with Angular js for my project. Things are working fine and data is properly sent to client side when there is no error at Java side. But in case there is an exception at java side then depending upon the exception i want to return my message to the user.My response text is not getting transmitted to the client side. Any help will be appreciated. Code is provided above
Here in above e.getMessage, i get my custom message which i have set in mu service layer and throws the exception from there. But in the client side in error message i get all the values as undefined.
I assume that in angular js when an error occurs, a JSON is expected and not html/text
So, convert the exception to json.
You can create a class
ie
class ClassErrorMessage {
private String errorCode;
private String errorMessage;
ClassErrorMessage() {
}
//getters and setters
}
and then
catch (C2PCException e) {
ClassErrorMessage classErrorMessage= new ClassErrorMessage();
classErrorMessage.setErrorCode("some code that you may want");
classErrorMessage.setErrorMessage(e.getMessage());
String error = gson.toJson(classErrorMessage);
return new ResponseEntity<String>(error,HttpStatus.SERVICE_UNAVAILABLE);
}
and let me know if this worked for you

Google App Engine. Channel API. The provided token is invalid.

I've been trying to make an application for calling browser to browser using WebRTC. I wrote a simple servlet for creating channel:
PrefClubChannelServletServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String channelKey = req.getParameter("userid");
resp.addHeader("Access-Control-Allow-Origin", "*");
ChannelService channelService = ChannelServiceFactory.getChannelService();
String token = channelService.createChannel(channelKey);
resp.setContentType("text/plain");
resp.getWriter().println(token);
}
}
I've deployed it in Google App Engine.
In my web application I've got a page with Java script, similar to https://apprtc.appspot.com. In my code Caller calls prepare(1), and Callee – prepare(0).
function prepare(ini) {
initiator = ini;
card = document.getElementById("card");
localVideo = document.getElementById("localVideo");
miniVideo = document.getElementById("miniVideo");
remoteVideo = document.getElementById("remoteVideo");
resetStatus();
console.log("Try to get token");
getToken();
}
function getToken() {
var token;
if (initiator) {
var xhr = new XMLHttpRequest();
var url = 'http://pref-club.appspot.com/prefclubchannelservlet?userid=GGGG';
xhr.open('POST', url, true);
// Specify that the body of the request contains form data
xhr.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xhr.send(url);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
token = xhr.responseText;
console.log("token = " + token);
document.getElementById("token").value = token;
openChannel(token);
doGetUserMedia();
}
};
} else {
token = document.getElementById("token").value;
console.log("token = " + token);
openChannel(token);
doGetUserMedia();
}
};
So, both Caller and Callee use the same token to open channel, and indeed they open channel, got media and made RTCPeerConnection
function openChannel(channelToken) {
console.log("Opening channel.");
var channel = new goog.appengine.Channel(channelToken);
var handler = {
'onopen': onChannelOpened,
'onmessage': onChannelMessage,
'onerror': onChannelError,
'onclose': onChannelClosed
};
socket = channel.open(handler);
}
The main problem is that event handler onChannelMessage doesn't work. I don't see any S->C: in console log. Callee doesn't see offer by Caller.
Then, I refreshed my servlet, redeployed it, and discovered I can't open channel at all. While Opening channel I'm getting Uncaught Error:
The provided token is invalid.

Resources