Download MS Excel/Word via AngularJS call to a REST service - angularjs

I have an AngularJS application that sends a POST request to a REST service (onClick method of a button). The POST request contains a JSON object with various settings. The REST service uses those settings to create a MS Word/Excel file.
At the moment the REST service sends the contents of the file back as a byte stream (in response to the previously mentioned POST request). When the file arrives I want a save-file-dialog to show up, where I can save the file. The backend is a Spring Boot app using Spring-MVC.
Can this be done in AngularJS?

If you can't use something like location.href to get your data to the server instead of post it, then check it out others using html 5:
more info AngularJS $http-post - convert binary to excel file and download
$http({
url: 'your/webservice',
method: 'POST',
responseType: 'arraybuffer',
data: json, //this is your json data string
headers: {
'Content-type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
}).success(function(data){
var blob = new Blob([data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
saveAs(blob, 'File_Name_With_Some_Unique_Id_Time' + '.xlsx');
}).error(function(){
//Some error log
});

This is the Controller function I ended up using:
#RequestMapping(value = "/downloadDocx", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.CREATED)
public void downloadDocx(#RequestBody DocxInputBean docxInput,
HttpServletResponse response) throws Exception {
File docxFile = outputManager.createDocxProfile(docxInput);
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
InputStream is = new FileInputStream(docxFile);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
is.close();
}

Related

Sending a "binary file" with AngularJS

I'm trying to upload a "binary file" from my cordova app into the imgur.com REST API using AngularJS.
But I'm not sure how I should format my request and what the "binary file" format is. From what I understand, a binary file is any thing that is not plain-text.
This is how I get file data from the local file system. It returns a blob instance. This part works fine.
var request = {
'url': 'file:///my/path/tmp/cdv_photo_025.png',
'options': {
'responseType': 'blob' // also tried 'arraybuffer', no diff.
}
}
var handler = function(response) {
window.myBlobData = response.data;
// handles the response
}
$http.get(request.url, request.options).then(handler);
Then later, I am using this to upload the blob to imgur, but this not working. I get a 400 (Bad Request). I am assuming the content-type, the disabling of the automatic encoding AngularJS does with transformRequest, and of course the binary data:
var request = {
'url': 'https://api.imgur.com/3/upload',
'options': {
'headers': {
'Authorization': 'Client-ID ***********',
'Content-Type': 'application/octet-stream',
},
'transformRequest': []
},
'data': {
'image': window.myBlobData, // a binary file
'type': 'image/png'
}
}
var handler = function(response) {
// handles the response
}
$http.post(request.url, request.data, request.options).then(handler);
For an image upload request with Imgur's API, you can't simply include the Client-ID in the header. If you were instead requesting public read-only information, then that would've been adequate.
If you haven't already, refer to the section on authorization in the Imgur API documentation.
Basically, you'll need to obtain an access token for the user for which you'll be uploading images on behalf of. As suggested by the documentation, you'll want to redirect or open a pop-up window to the below URL.
https://api.imgur.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=access_token
Then, once you've obtained the access token, ensure your upload requests use it:
'Authorization': 'Bearer access_token'
Furthermore, simply use your blob data as the argument for the request (i.e. don't wrap it with the image and type properties).

How to set request part for POST request with angular-file-upload and Spring?

Unfortunately this answer does not help me. The problem appears to be that the request parameter file is not present in my POST request for some reason.
I am trying to upload a file, any file whether it's a binary file or a text file, in a POST request. The REST controller reveals:
#PostMapping(WordEmbeddingApiPaths.UPLOAD_MODEL)
#RequestMapping(method=RequestMethod.POST, headers={"Content-Type=multipart/form-data"})
public ResponseEntity<WordVectorListDto> uploadModel(
#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
LOGGER.debug("POST uploadModel");
return new ResponseEntity<WordVectorListDto>((WordVectorListDto)null, HttpStatus.OK);
}
and on the client I am running:
var uploader = $scope.uploader = new FileUploader({
url: 'http://localhost:8080/rest-api/dl4j/we/uploadModel'
});
uploader.onAfterAddingFile = function($modelFile) {
console.info('onAfterAddingFile', $modelFile);
var fd = new FormData();
fd.append('file', $modelFile.file);
$http.post($modelFile.url, fd, {
headers: {
'Content-Type': 'multipart/form-data'
},
params: {'file' : $modelFile.file}
})
.then(
function (data) {
alert("upload success");
},
function (data, status) {
alert("upload error");
}
);
};
However, I am getting 400 Bad Request as server response.
Any idea what the problem is?
Update:
I saw that an internal exception got thrown on the server side stating:
org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present
I thought that I am setting this already - how can I make this right?
Posting FormData with AngularJS
When doing a POST with a FormData API object, it is important to set the Content-Type header to undefined.
var fd = new FormData();
fd.append('file', $modelFile.file);
$http.post($modelFile.url, fd, {
headers: {
//'Content-Type': 'multipart/form-data'
'Content-Type': undefined
},
//params: {'file' : $modelFile.file}
})
When the XHR send() method gets a FormData object created by the FormData API it automatically sets the content type to multipart/form-data and includes the proper boundary.
By having the AngularJS framework override the content type, the boundary is not set properly.
Debugging Small Programs
This question is an example of putting several things together without debugging each part.
This question has several unknown code components:
An undebugged AngularJS POST method
An undebugged Spring Backend
An undebugged mysterious AngularJS service
This answer pointed out errors with the AngularJS POST method but there are a couple of other unknowns. Is the Spring backend working properly? Is the mysterious FileUploader service being used correctly?
Debugging involves isolating unknowns and testing them separately.
Does the Angular POST method work with a known backend such as HTTP BIN - HTTP Request & Response Service?
Does the Spring backend work with an uploader that has been tested?
For more information, see How to debug small programs.
if you are using #EnableAutoConfiguration then you need to do the following as discussed here https://github.com/spring-projects/spring-boot/issues/2958
#EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
define the following beans
#Bean(name = "multipartResolver")
public CommonsMultipartResolver commonsMultipartResolver(){
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(50*1024*1024);
return resolver ;
}
#Bean
#Order(0)
public MultipartFilter multipartFilter(){
MultipartFilter multipartFilter = new MultipartFilter();
multipartFilter.setMultipartResolverBeanName("multipartResolver");
return multipartFilter;
}

Angularjs: how to properly save a blob pdf file recieved from the server

The recieved file goes through $http and i need to save the response data into a file, i am using angular-file-saver, the recieved files are pdf docx, but viewing the saved pdf file shows nothing on the reader, while other downloaders like PostMan does save it right.
the function that takes care of saving has this code:
function saveFile(data, header){
var extensions = {
"application/pdf": ".pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx"
}
var file = new Blob([data], {type: header});
FileSaver.saveAs(file, documentsShow.document.name + extensions[header]);
}
data is the body data retrieved from $http success and header is the Content-Type also recieved from $http response
in case if it's needed, the $http code is like this:
$http({
method: "GET",
data: data, //This is sometimes null but it's not relevant for the application
url: "path/to/download"
}).then(function(data){
saveFile(data.data, data.header("Content-Type"));
});
Main problem I see here is that Angular will still be trying to parse the response as JSON.
You can modify this so it resolves with a Blob object
$http.get('path/to/download', {
responseType: 'blob'
}).then(function(res) {
FileSaver.saveAs(res.data, ...)
});
FYI, data is not used in GET requests.

how to use response.redirect in webapi+asp.net?

I want to redirect to another .aspx page from WebAPI. I have used this code but it is not working:
string url = "http://localhost:61884/UserList.aspx";
System.Uri uri = new System.Uri(url);
return Redirect(uri).ToString();
You don't. (or your description of the problem is not accurate)
Web API is meant to retrieve data or persist data, it is a way to interact with the server from the client without having to do the traditional form post or page request calls. The caller (javascript based on your question tag angularJs) needs to execute the redirect once the results from the call to the Web API are retrieved.
This is good SOC (separation of concerns), the business logic in the Web API should not care about routes (angularjs) / web pages.
Even if you wanted to the Web API, because of how its called, can't redirect the client.
Summary: The Web API code itself should not any type of redirecting of the client. The client should handle this.
Sample call to web api and redirect from angular code:
$http({
url: "/api/SomeWebApiUrl",
data: {},
method: "POST",
headers: { 'Content-Type': "application/json" },
responseType: "json"
}).then(function (response) {
if(response.data.somethingToCheck === someConditionThatWarrentsRedirect)
$window.location.href = "~/someOtherUrl/";
});
try something like this:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Hope that helps.
Redirect from asp.net web api post action
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

Resources