file not binding to angularjs service using FormData - angularjs

I am trying to upload a file using angularjs and spring 3, I have written a service which is not binding the selected file. I don't know what mistake I have been doing, please help me to solve this problem. I am using commonsmultipart for uploading the files. following are the fileUploadService and controller codes.
MyApp.service('fileUploadService', function ($http, $q) {
this.uploadFileToUrl = function (file, uploadUrl, formData) {
//FormData, object of key/value pair for form fields and values
var fileFormData = new FormData();
fileFormData.append('fileUpload', file);
// console.log(formData);
fileFormData.append('name', formData.name);
fileFormData.append('email', formData.email);
fileFormData.append('password', formData.password);
fileFormData.append('mobile_no', formData.mobile_no);
fileFormData.append('register-submit', 'Register Now');
var deffered = $q.defer();
$http.post(uploadUrl, fileFormData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (response) {
deffered.resolve(response);
}).error(function (response) {
deffered.reject(response);
});
return deffered.promise;
}
});
Spring Controller:
#SuppressWarnings({ "unused", "static-access" })
#RequestMapping( value="/RegisterCandidate" , method = RequestMethod.POST)
private String RegisterCandidate(HttpServletRequest request,
HttpServletResponse response,
#RequestParam CommonsMultipartFile[] fileUpload ) throws Exception{
System.out.println("In method");
String email = request.getParameter("email");
System.out.println("email==============="+email);
String Password = request.getParameter("password");
String usr_name = request.getParameter("name");
String mobile_no = request.getParameter("mobile_no");
Date dateentry = new Date();
java.sql.Timestamp entry_date = new Timestamp(dateentry.getTime());
Users_Pojo usr = new Users_Pojo();
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload){
usr.setFilename(aFile.getOriginalFilename());
usr.setFile_data(aFile.getBytes());
System.out.println("aFile.getBytes()======"+aFile.getBytes());
System.out.println("aFile.getInputStream()======"+aFile.getInputStream());
System.out.println("aFile.getStorageDescription()======"+aFile.getStorageDescription());
System.out.println("aFile.getSize();======"+aFile.getSize());
System.out.println("aFile.getContentType();==="+aFile.getContentType());/* */
}
}
MD5CodeGenerator md5 = new MD5CodeGenerator();
usr.setUc_password(md5.convertToMD5(Password));
usr.setUc_name(email);
usr.setUc_contact_person(email);
usr.setUc_phone_no(BigInteger.valueOf(Long.parseLong(mobile_no)));
usr.setUc_email_id(email);
usr.setUc_type_id(1);
usr.setUc_active(1);
usr.setValid_from(null);
usr.setValid_to(null);
usr.setDesignation("jobseekar");
usr.setIp_address("164.100.19.79");
usr.setUser_location(1);
usr.setEntry_date(entry_date);
scm_service.save(usr, email);
return "success";
}

Related

Upload Image from angularjs using Springboot to FTP

I am trying to pick a file and upload it to FTP.
For now I get the a 415 (media type unsupported) error when consuming springboot service in angularjs when sending the image.
This is my angular controller:
Controllers.controller('UploadCtrl', [ '$scope', '$http',
function($scope, $http) {
$scope.doUploadFile = function() {
var file = $scope.uploadedFile;
var url = "/ui/upload";
var data = new FormData();
data.append('uploadfile', file);
var config = {
transformRequest : angular.identity,
transformResponse : angular.identity,
headers : {
'Content-Type' : undefined
}
}
$http.post(url, data, config).then(function(response) {
$scope.uploadResult = response.data;
}, function(response) {
$scope.uploadResult = response.data;
});
};
} ]);
My Service Controller JAVA:
#POST
#Path("/upload")
#Consumes("multipart/form-data")
public String upload(#RequestParam("uploadfile") MultipartFile file) throws Exception {
try {
return "You successfully uploaded - " + file.getOriginalFilename();
} catch (Exception e) {
throw new Exception("FAIL! Maybe You had uploaded the file before or the file's size > 500KB");
}
}
For now just getting the file name. What am 'I doing wrong when consuming the POST ?
Thank you in advance
try this:-
HTML
<img ng-src="{{profilePicturePath}}" class="img-responsive"
alt="Image Not found" style="height:150px; width: 150px;">
<input type="file" class="form-control" style="display: none;"
file-model="profileFile" multiple name="profileFile"
id="profileFile" accept="image/*"/>
JS
$scope.profileFile = null;
$scope.$watch('profileFile', function (profileFile) {
if (profileFile && profileFile.name) {
if (profileFile.size / 1012 < 512) {
if (profileFile.type.startsWith("image/")) {
uploadProfilePicture(profileFile);
}
}
}
});
function uploadProfilePicture(profileFile) {
aspirantService.uploadProfilePicture(profileFile).then(function (response) {
getProfilePicturePath();
});
}
this.uploadProfilePicture = function (file) {
var fd = new FormData();
fd.append("doc", file);
return $http.post(Server.url + 'aspirant/pic/', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
};
and JAVA
#Path("pic")
#POST
#Consumes(MediaType.WILDCARD)
public Response uploadProfilePicture(MultipartFormDataInput input, #Context UserSession session) {
for (Map.Entry<String, List<InputPart>> entry : input.getFormDataMap().entrySet()) {
List<InputPart> list = entry.getValue();
for (Iterator<InputPart> it = list.iterator(); it.hasNext();) {
InputPart inputPart = it.next();
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
String fileName = RequestHeaderInfo.getFileName(header);
String contentType = RequestHeaderInfo.getContentType(header);
InputStream inputStream = inputPart.getBody(InputStream.class, null);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
//here code for write file
return Response.ok(proxy).build();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error while getting document!", ex);
}
}
}
return Response.ok().build();
}

ng-file-upload : send List as additional data

I want to upload a file using ng-file-upload, and send at the same time a list of values (type Long).
I have done that:
Client side
vm.uploadFiles = function(file, errFiles) {
$scope.f = file;
$scope.errFile = errFiles && errFiles[0];
if (file) {
file.upload = Upload.upload({
url: '/api/sendMailCra',
fields: {'collaborateursId':vm.collaborateursId},
file: file
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
vm.clear();
}, function (evt) {
});
}
}
Server side
#RequestMapping(value = "/sendMailCra",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public void upload(#RequestParam("collaborateursId") List<Long> collaborateursId, #RequestParam("file") MultipartFile file) throws IOException {
log.debug("REST send mail to Collaborateurs : {}"+collaborateursId);
}
I am getting a
500 Internal server error
with no error log on server side.
How can I pass my List from client to server side?
Thanks
By using form data we can send File and data from angular-controller to server.
vm.uploadFiles = function(file, errFiles) {
$scope.f = file;
$scope.errFile = errFiles && errFiles[0];
var data = new FormData();
data.append("uploadFile ", file);
data.append("collaborateursId ", vm.collaborateursId);
if (file) {
file.upload = Upload.upload({
url: '/api/sendMailCra',
data:data,
headers: {'Content-Type': undefined}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
vm.clear();
}, function (evt) {
});
}
}
In Controller using mutipartRequest
#RequestMapping(value = "/sendMailCra",
method = RequestMethod.POST,
)
#Timed
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
String collaborateursId= request.getParameter("collaborateursId");
next converted the request to multipartRequest for get th file
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Iterator<String> fileNames = mRequest.getFileNames();
while (fileNames.hasNext()) {
// HashMap<String, String> hashMap = new HashMap<String, String> ();
MultipartFile file = mRequest.getFile(fileNames.next());
store file into your prefered location....
}
log.debug("REST send mail to Collaborateurs : {}"+collaborateursId);
}
We can set File size limit in the spring configurationFile link
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size -->
<beans:property name="maxUploadSize" value="100000" />
</beans:bean>
see this link

Not able to get AngularJs fileData from HttpServletRequest at server side

AngularJS Client Side:
userTab.factory('someService', ['apiService','$rootScope', function(apiService, $rootScope){
return {
updateData : function (someObj){
return apiService.request({
apiMethod: 'user/v1/updateData',
httpMethod: 'POST',
fileData: JSON.stringify(someObj)
}).error(function(data, status) {
throw "updateData error: " + status;
});
}
}
}]);
Server Side Code:
Update.java
#Controller("user")
#RequestMapping(value = "/user/v1")
public interface Update
{
#ResponseBody
#ResponseStatus(HttpStatus.CREATED)
#RequestMapping(value = "/users/{username}/updateData", method = POST)
String updateData(HttpServletRequest request, HttpServletResponse response, #PathVariable("username") String username, #RequestBody UserUpdate userUpdate);
}
UpdateImpl.java
#Override
#Transactional
public String updateData(HttpServletRequest request, HttpServletResponse response, #PathVariable("username") String username,
#RequestBody UserUpdate userUpdate) {
String requestBody = ServletUtils.getRequestBody(request);
logger.info("RequestBody: "+requestBody);
return new String("true");
}
Response:
RequestBody: {}
So as you see that RequestBody is coming as blank as I haven't given anything in params within angularjs API call.
So how to get the fileData which is not in params here?
UPDATE:
My fileData is a normal json array just like this:
{
"todo" : "Dinner",
"user" : [
{
"name" : "username",
"password" : "passwordabc"
}
],
"notes : "some notes"
}
And I have created it in an angularjs as follows:
var object = {};
object.todo = "Dinner";
object.notes = "some notes";
userArray = [{
name: 'myname',
password: 'password'
}];
object.user = userArray
UPDATE:
apiService.js
'use strict';
apiModule.factory('apiService', ['$http', '$q', 'LoginService','XSSValidator', function($http, $q, loginService, XSSValidator) {
var basePath="https://somesite.com/userApi/";
var _httpMethod="POST";
var caching=false;
var latestRequest={};
$http.defaults.withCredentials = true;
return{
if(typeof bundle.fileData != "undefined"){
return $http({
cache: caching,
method: bundle.httpMethod,
headers:{"Content-Type":contentType},
url:basePath+bundle.apiMethod,
data:dataStr,
transformRequest: angular.identity,
transformResponse:bundle.transformResponse,
timeout: canceller.promise
}).success(function(data, status, headers, config) {
//check to see if request has been redirected to login page, suggesting user has been logged out
if(typeof data==='string' && data.substr(0,44)==='<html><head><title>Login Page</title></head>'){
window.location.href="/login" + window.location.search;
}
var req;
if(config.data !== ""){
var requestArr=config.url.split(config.data);
req=requestArr[0].split("?")[0];
}
else{
req=config.url;
}
if(config.data !== "" && !data.fault){
if(Object.prototype.toString.call(data) == "[object String]"){
var msg = XSSValidator.validate("Response ", data);
if (msg != null) {
return $q.reject({ message: msg });
}
}else if(config.headers["Content-Type"] == "application/x-www-form-urlencoded" || config.headers["Content-Type"] == "application/json"){
eval(data);
}
}
if(latestRequest[req]!==config.url){
//cancel promise
return $q.reject({ message: 'Rejecting this promise' });
}
}).error(function(data, status, headers, config) {
if(status===401){ //user has been logged out server-side. redirect to login pg
window.location.href="/login" + window.location.search;
}
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}

How to make Spring REST service to accept multipart file data sent by the Angular Controller?

I'm trying to post a file from Angular controller to the backend. But Spring REST controller is receiving null.
JS
myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){
$scope.uploadFile = function(){
var formData=new FormData();
formData.append("file", $scope.myFile);
alert("Hi");
$http({
method: 'POST',
url: 'upload',
headers: {'Content-Type': undefined},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
}).success(function(data, status) {
console.log('file is ' );
console.dir(data);
})
.error(function(data, status) {
});
}
}]);
Spring-REST Controller
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String upload(#RequestBody MultipartFile file) {
System.out.println(file);
}
I also tried with public #ResponseBody void uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) but it's of no use. I have declared multipartResolver in the configuaration file too. Any Idea on this? I'm desperately looking for a solution.
Here is a piece of code that works for me:
Spring-REST Controller
#RequestMapping(value = "/api/users/{id}/image", method = RequestMethod.POST)
#ResponseBody
public boolean uploadUserImage( #PathVariable("id") Long id, #RequestParam("file") MultipartFile file ) {
return userService.saveUserImage(id, file);
}
and on the front-end you could do something like this
Angular Controller
//the image
$scope.uploadme;
$scope.uploadImage = function() {
var fd = new FormData();
var imgBlob = dataURItoBlob($scope.uploadme);
fd.append('file', imgBlob);
$http.post(
'/upload',
fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
)
.success(function(response) {
console.log('success', response);
})
.error(function(response) {
console.log('error', response);
});
}
//you need this function to convert the dataURI
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {
type: mimeString
});
}
Assuming that the http request is correct the problem must be at the Spring controller. I think you have to change upload(#RequestBody MultipartFile file) to upload(#RequestParam("file") MultipartFile file). So it will be like this:
#RequestMapping(value="/upload", method=RequestMethod.POST)
#ResponseBody
public void upload(#RequestParam("file") MultipartFile file) {
System.out.println(file);
}
Also in your function you have it return String but you are not returning one. So i assume you are doing something else and you removed the code in order to post the question and missed the return, otherwise it wouldn't even build.
Lastly you could check this answer that i gave to a similar problem.

not able to upload image to java restful web service

My angular controller is
app1.controller('kyc_controller', ['$scope', '$http', function($scope, $http)
{
$scope.uploadFile = function(){
var file = $scope.myFile;
var fd = new FormData();
fd.append('file', file);
$http({
method : 'POST',
url: '/GngService/api/GoNoGo/upload_file',
params : {'filename':'pancard'},
data : fd,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + JSON.stringify(data));
});
};
}]);
and my server side api method is
#POST
#Path("/upload_file")
#Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED})
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response upload(#FormDataParam("file") InputStream ins, #FormDataParam("filename") String filename, #FormDataParam("file") FormDataContentDisposition contentDispositionHeader ) throws IOException {
System.out.println(filename);
BufferedImage image = ImageIO.read(ins);
// ImageIO.write(image, "jpg", new File("/../../fileName"));
String result = "{'status' : 'ok'}";
String json = new Gson().toJson(result);
return Response.ok(json.toString(), MediaType.APPLICATION_JSON).build();
}
It shows Unsupported media type...please help me to upload images....thanks in advance

Resources