Download file using angular js by calling spring rest api - angularjs

I have a Spring Controller which send file in response
#RequestMapping(value = "/downloadData", method = RequestMethod.GET)
public void downloadData(HttpServletResponse response) throws IOException
{
File dataJSONFile = dataDownloadService.createAndWriteFile();
response.setContentType("application/text");
response.setContentLength(new Long(dataJSONFile.length()).intValue());
response.setHeader("Content-Disposition", "attachment; filename="data.json");
FileCopyUtils.copy(new FileInputStream(dataJSONFile),
response.getOutputStream());
}
If I write in browser url, //localhost:8080/myproject/rest/downloadData It downloads the file.
Now, want to download the file when click on button in using angular js.
I have written following code in angular js to download file
angular
.module('myApp.services')
.factory(
'DataDownloadService',
function($resource) {
"use strict";
return {
"query" : function() {
var ret, restResource;
restResource = $resource(
'/sand-pp/api/rest/downloadData',
{}, {
"query" : {
"method" : "GET",
"isArray" : true,
headers:
{
'Content-Type': 'application/text',
'Content-Disposition': 'attachment; filename=data.json'
}
}
});
ret = restResource.query();
return ret;
}
};
});
When I call above service nothing is happening but if I print data in callback function is printing data in console.
How to download file in angular js by calling Spring REST api?

I would use a service for the rest call. Try this following:
window.location.href = DataDownloadService.query();
It should prompt the browser to download the file (because of Content-Disposition header).

Related

Uploading document from angularjs to springboot

Angularjs $http.post gives a 404 exception but all the other methods works fine with the same codes, i am trying to upload a file via spring boot
The same codes works fine in my other project i did about last year, and the same $http.post works when i send information without a file
service.js
function addCompanyDoc(file, id) {
var deferred = $q.defer();
var data = new FormData();
data.append('file', file);
var config = {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
}
console.log('appService file ');
console.dir(file); //cheking if file is available
$http.post('http://localhost:8080/listed/welcome/company/doc/' + id,
data, config)
.then(function(response) {
deferred.resolve(response.data);
},
function(errResponse) {
alert(errResponse.data.errorMessage);
console.error('Error while uploading company doc', errResponse);
this.flag = 'failed';
deferred.reject(errResponse);
});
return deferred.promise;
}
spring boot
#RequestMapping("/welcome")
public class controllers{
#RequestMapping(value = "/company/doc/{id}", method =
RequestMethod.POST, consumes = {"multipart/form-data" })
#ResponseBody
public ResponseEntity<Void> saveCompanyDoc(#RequestParam("file")
MultipartFile file, #PathVariable final int id){
//....uploading to DB
}
}
angularjs sends a document to spring boot and spring uploads to the DB / sends to a folder.
Working fine :-) with angularjs 1.7 & spring boot 2.*
Thanks for all the comments the above code is correct,
I created a dummy table and controller to test the app.
And it gave the same 404 error and i recalled a few weeks back i added an "admin folder" to handle CMS and directed all the ROLES to the "folder" and it blocked all the users from doing data POSTING. SO i just had to fix my WebSecurityConfig class :-)

Rest Service not working when deployed on AWS

This is my Rest Service.
#RestController
public class ProjectController {
#RequestMapping(method = RequestMethod.GET, value = "/getProjects")
public ArrayList<Project> getProjects() {
ArrayList<Project> projectList = new ArrayList<Project>();
ProjectDao obj = new ProjectDao();
projectList = obj.getProjects();
return projectList;
}
}
And this is my Angular script to invoke this service.
$http({
method: "GET",
url: "/getProjects"
})
.then(
function success(response) {
...
},
function error {
alert("Error");
}
);
These are working fine when I run the application on my localhost. But, it fails when I deploy my spring-boot application on AWS and run it on server. Server returns HTTP Status 404 - The requested resource is not available instead of JSON data when I enter the URL of the service in browser. What's the problem here?
Mkyong solved it.
Here is the solution.
add #CrossOrigin annotation with #RestController

ASP.NET API Controller POST/Redirect/Get

I would like to use the P/R/G design with this API, using AngularJS on the client side. Here is my API method:
[HttpPost]
public HttpResponseMessage UpdateRaw(HttpRequestMessage request)
{
//do stuff...
var res = request.CreateResponse(HttpStatusCode.Redirect);
var authority = request.RequestUri.Authority;
var uri = string.Concat(authority, "/api/DataApi/GetRaw");
res.Headers.Location = new Uri(uri);
res.Headers.Add("Access-Control-Allow-Origin", "*");
return res;
}
I have another method in this controller (DataApiController) which is called GetRaw(). Basically I want the client to issue a POST, call this method, then get redirected to the GET method. Here is my JS code:
//get the data and build the js rep
$http({
method: 'POST',
url: '/api/DataApi/UpdateRaw',
headers: {
'Content-Type': undefined
},
data: {
test: "test"
}
}).then(function (result) {
console.log("RAW--------------");
console.log(result.data);
// do stuff...
}, function () { console.log("DIDN'T WORK"); });
When I issue the POST, however, my browser console says "The request was redirected to a URL ('localhost:25498/api/DataApi/GetRaw') which has a disallowed scheme for cross-origin requests." I am aware of this answer, but that had the same result.
I found another website somewhere which suggested adding the line
res.Headers.Add("Access-Control-Allow-Origin", "*");
but that does not seem to work either.
I am new to ASP.NET and Web Dev in general, so any ideas would be appreciated. Thanks.

uploading files using angularjs and spring boot

I have an angularjs application deployed in a server, and a spring boot application deployed in another server.
in my angularjs application I have a form that uploads a file and send it via a rest controller, this controller then saves this file inside a folder in the server where the spring boot application is deployed.
this is my rest controller :
#CrossOrigin(origins="*")
#RestController
public class Upload {
#RequestMapping(value="/imageUpload", method = RequestMethod.POST)
public void UploadFile(MultipartHttpServletRequest request) throws IOException {
Iterator<String> itr=request.getFileNames();
MultipartFile file=request.getFile(itr.next());
String fileName=file.getOriginalFilename();
File dir = new File("C:\\file");
if (dir.isDirectory())
{
File serverFile = new File(dir,fileName);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(file.getBytes());
stream.close();
}else {
System.out.println("not");
}
}
}
and this my angularjs controller which sends the file :
$scope.validerOffre= function(){
var file = $scope.fileUpload;
var uploadUrl = "/imageUpload";
fileUploadService.uploadFileToUrl(file, uploadUrl);
};
this controller then call the fileUploadService :
capValueRecruitApp.service('fileUploadService', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post('http://localhost:8080' + uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
});
and in my angularjs application I want to display the files that I uploaded but I cant do that since the files were uploaded in the spring boot application server, which is another server .
so my question is how can I save the files that I uploaded in a folder in the angularjs application server instead of the server where the spring boot application is deployed.
You basically have two solutions :
1: you create a new #RequestMapping that takes the filename ( or even better an id returned by your fileUpload controller) and that returns the file.
something like this :
#RequestMapping(value="/imageDownload", method = RequestMethod.POST)
public void downloadFile(#RequestParam(value = "fileName", required = true) String fileName,HttpServletResponse response) throws IOException {
File dir = new File("C:\\file");
File fileToDownload = new File(dir,fileName);
if (dir.isDirectory() && fileToDownload.exists()){
//read fileToDownload and send stream to to response.getOutputStream();
}else {
System.out.println("no such file "+ fileToDownload.toString());
response.sendError(404);
return;
}
}
Then you call http://localhost:8080/imageDownload?filename=yourUploadedFile.jpg
2: When you save the file in your upload, save it somewhere where your webserver has direct access.
If our angularjs files are served by your spring application, you could add a new folder in spring.resources.staticLocations in the application.properties file. (see this : http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content )

Upload image to server angularjs

I need to upload an image taken from my mobile device to my server. I found the angular-upload library to which makes reference. I need to do is to transform the image base 64, send it by post to my server because the server is where I will work with her. And the other, send from my server and work it from the application to run.
var server = URL_BASE+'addView/';
var trustAllHosts = true;
var ftOptions = new FileUploadOptions();
ftOptions.fileKey = 'file';
ftOptions.fileName = $scope.imagen.substr($scope.imagen.lastIndexOf('/') + 1);
ftOptions.mimeType = 'image/jpeg';
ftOptions.httpMethod = 'POST';
console.log(ftOptions);
$cordovaFileTransfer.upload(encodeURI(server), $scope.imagen, ftOptions, trustAllHosts)
.then(function(result) {
console.log(result)
}, function(err) {
// Error
console.log(err);
}, function (progress) {
});
ionic file transfer
I'm personally using Cordova file transfer for upload & download content from a server.
Base64 encoding
Don't know where is your image stored and how you retrieve it, but, either you specify that the image is base64 encode into the HTML file delimiter
OR
You transform your image using a canvas
See that post for more info : https://stackoverflow.com/a/20285053/3687474
You haven't specified what you really need so:
Here you have a factory
//Factory you register on your module
angular
.module('myApp')
.factory('sendBase64Image', sendBase64Image)
function sendBase64Image($http) {
var urlBase; //url to be filled in
var base64 = {};
base64.sendBase = function (baseImg) {
var request = $http({
method: "post",
url: urlBase,
headers: {
'Content-type': 'application/json'
},
data : baseImg
});
}
return base64;
}
You should then inject it via dependency injection to your controller and perform call to the server.
If you want to do something with a response use success() method to handle promise response.

Resources