uploading files using angularjs and spring boot - angularjs

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 )

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 :-)

React upload a file to spring controller

We have a Java spring-boot based server and a react JS UI app.
And we need to implement a file upload from the react app to the server.
Server controller code:
#RequestMapping(value = "/aaa/{id}/upload", method = RequestMethod.PUT, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Object uploadFile(#PathVariable("id") Integer id, #RequestParam("file") MultipartFile file, HttpServletRequest request) {
...
logic
...
}
With postman, we can upload the file successfully. We can't do it via the react JS app.
This is react JS upload file code:
uploadFile(file, type) {
const formData = new FormData();
formData.append('file', file);
return axios.put(`aaa/1/upload`, file, {
headers: {
'content-type': 'multipart/mixed; boundary=--ABC123Boundary'
}
})
.then(() => {
NotificationsManager.info('File successfully uploaded.')
})
.catch((err) => {
NotificationsManager.error(err.message, `Error in uploading file`);
});
}
We tried with boundary, without boundary, with default boundary... nothing works.
UPDATE: We get this error:
"Bad Request"
exception:
"org.springframework.web.multipart.support.MissingServletRequestPartException"
message:"Required request part 'file' is not present"
What did we do wrong?
Regards,
Ido

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

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();
}

Open a PDF in a new window of the browser with angularjs

I'm new to angular js and I wish to open a PDF document in a new window of the browser after pressing a button.
I make a GET request with $http.get() at front end, at backend there is a Java rest service that respond to the GET and generates a PDF. I wish to open this PDF on the browser.
If is not possible to open the PDF in this way then at least open any PDF with AngularJs, how could I do this?
#GET
#Path("/printPdf")
public Response printService(){
//generates the pdf
File reportFile = new File(filePath);
String name = reportName + "." + "pdf";
ResponseBuilder response = Response.ok(new TemporaryFileInputStream(reportFile));
response.header("Content-Disposition", "attachment; filename=" + name);
response.header("Content-Type", "application/pdf");
response.header("Access-Control-Expose-Headers", "x-filename");
response.header("x-filename", name);
return response.build();
}
this is what there is at backend to generate the response in the rest service.
If you had something like this:
var myPdfUrl = 'something'
$http.get(myPdfUrl);
Do this instead:
var myPdfUrl = 'something'
$window.open(myPdfUrl);
If instead you have something like this:
$http
.get(generatePdfUrl)
.then(function(data){
//data is link to pdf
});
Do this:
$http
.get(generatePdfUrl)
.then(function(data){
//data is link to pdf
$window.open(data);
});
Maybe this can help,in the case of you have something like this :
$http.get('generatePdfUrl')
.then(function (data) { // data is your url
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
});
Then use your service in controller and do
$window.open(fileURL);

Download file using angular js by calling spring rest api

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).

Resources