uploading file using angularjs and spring - angularjs

I have an input type="file" as following :
<input id="identityDocument" name="identityDocument" ng-model="candidature.identityDocument"
ui-jq="filestyle" type="file" class="filestyle input-lg"
file-model="uploadIdentityDocument"
ui-options="{
buttonText: '{{'ACTIONS.UPLOAD' | translate}}',
iconName: 'fa fa-inbox'
}"
accept="image/*" valid-file required>
to let this input file known in the scope I use this directive :
.directive('fileModel',function($parse){
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
});
So I want when I submit this form to upload the file in it as following :
let file = $scope.uploadIdentityDocument;
let fd = new FormData();
fd.append('file', file);
$http.post('http://localhost:8080/fileUpload', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
in the server side this my rest service :
#RestController
public class UploadService {
#Autowired
IUploadMetier uploadMetier;
#RequestMapping(value="/fileUpload", method = RequestMethod.POST)
public ResponseEntity<String> UploadFile(MultipartHttpServletRequest request) {
String response = uploadMetier.uploadFile(request);
if(response.equals("false")){
return new ResponseEntity<>("There was an error uploading this file: " + response + " to the server :-(", HttpStatus.INTERNAL_SERVER_ERROR);
}else{
return new ResponseEntity<>("The file: " + response + " has uploaded successfully :-)", HttpStatus.OK);
}
}
}
and this is the function which uploads the file :
public String uploadFile(MultipartHttpServletRequest request) {
Iterator<String> itr=request.getFileNames();
MultipartFile file=request.getFile(itr.next());
String fileName=file.getOriginalFilename();
File dir = new File("\\MyPath");
if (dir.isDirectory())
{
File serverFile = new File(dir,fileName);
BufferedOutputStream stream = null;
try {
stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(file.getBytes());
stream.close();
} catch (IOException e) {
e.printStackTrace();
return "false";
}
}else {
return "false";
}
return fileName;
}
but then I get this error message :
java.util.NoSuchElementException: null
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:713) ~[na:1.8.0_73]
at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:734) ~[na:1.8.0_73]
at org.capvalue.fme.metier.mpl.UploadMetierImpl.uploadFile(UploadMetierImpl.java:19) ~[classes/:na]
at org.capvalue.fme.web.rest.UploadService.UploadFile(UploadService.java:23)
the line UploadMetierImpl.java:19 refers to : MultipartFile file=request.getFile(itr.next());
how can I solve this ?
Edit :
I just noticed that when I console.log $scope.uploadIdentityDocument I get undefined, and I don't know why I'm getting that !

The error was that the $scope.identityDocUpload was not defined, the solution was to delete that fileModel directive I used and I added this to my input :
onchange="angular.element(this).scope().setFile(this,'identityDocumentUpload')"
The setFile function :
$scope.setFile = function(element, name) {
$parse(name).assign($scope, element.files[0]);
}

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

Getting error while uploading file : The current request is not a multipart request in spring 4 and angular js

I am using spring 4 and angularjs, for multipart have used commons-fileupload-1.3.2.jar and commons-io-2.4.jar
I am getting error "org.springframework.web.multipart.MultipartException: The current request is not a multipart request" while uploading the file
application-servlet.xml has entry :
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20971520" />
</bean>
html file : `
<div class="padding-5 border-1">
<input type="file" id="uploadFileName"
size="60" class="filestyle width100per"
data-icon="false" file-model="importIdeaFile"
name="filename" required>
</div>`
angular controller :
$scope.saveFile = function(){
var filename = $scope.importIdeaFile.name;
var formdata = new FormData();
if(typeof $scope.importIdeaFile != 'undefined' && $scope.importIdeaFile != null && $scope.importIdeaFile !=''){
formdata.append("file",$scope.importIdeaFile);
formdata.append('data',new Blob([JSON.stringify($scope.uploadPopupData)], {
type: "application/json"
}));$http.post('loginData/uploadIdeafile',formdata,{headers: {'Content-Type': undefined}})
.then(
function(response,status) {
alert(status);
},
function(errResponse) {
alert(" Error while fetching User");
});
}
}`
Spring Controller :
#RequestMapping(value = "/uploadIdeafile", method = RequestMethod.POST, produces = "application/json")
public String uploadIdeafile(#RequestPart("file") MultipartFile formdata,
HttpServletRequest request) {
String methodName = "uploadIdeafile(#RequestBody MultipartFile formdata, HttpServletRequest request)";
String message = "true";
return message;}
created directory :
WebApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};}]);
I add"transformRequest: angular.identity" in http call and solved problem
$scope.saveFile = function(){
var filename = $scope.importIdeaFile.name;
var formdata = new FormData();
if(typeof $scope.importIdeaFile != 'undefined' && $scope.importIdeaFile != null && $scope.importIdeaFile !=''){
formdata.append("file",$scope.importIdeaFile);
formdata.append('data',new Blob([JSON.stringify($scope.uploadPopupData)], {
type: "application/json"
}));$http.post('loginData/uploadIdeafile',formdata,{headers: {'Content-Type': undefined}})
.then(
function(response,status) {
alert(status);
},
function(errResponse) {
alert(" Error while fetching User");
});
}
}`
New code :
$scope.saveFile = function(){
var filename = $scope.importIdeaFile.name;
var formdata = new FormData();
if(typeof $scope.importIdeaFile != 'undefined' && $scope.importIdeaFile != null && $scope.importIdeaFile !=''){
formdata.append("file",$scope.importIdeaFile);
formdata.append('data',new Blob([JSON.stringify($scope.uploadPopupData)], {
type: "application/json"
}));$http.post('loginData/uploadIdeafile',formdata,{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}})
.then(
function(response,status) {
alert(status);
},
function(errResponse) {
alert(" Error while fetching User");
});
}
}`

Error 404: Please upload an image - AngularJs

I am trying to upload files in Angular Js. I am following the below example https://plnkr.co/edit/CqIixHWefjYmDfmJPbNF?p=preview provided by #georgeawg in Pass file reader data to service in Angular Js
In index.cshtml
<input type="file" my-files="files" />
<input type="button" name="imageUploadButton" ng-click="uploadFiles()" value="Upload" />
In controller.js
angular.module('testApp.controllers', []).
controller('testApp.Controller', function ($scope, testAPIService, Excel, $timeout, $window, $location, $anchorScroll, $http, sharedDataService) {
var url = "https://siteUrl/UploadImage/";
var config = {
headers: {
"Content-Type": undefined,
}
};
$scope.uploadFiles = function () {
var file = sharedDataService.shared.files[0];
testAPIService.postUploadImage(file).success(function (response) {
alert(respone)
}); };
});
angular.module("testApp.Controller").directive("myFiles", function ($parse, sharedDataService) {
return function linkFn(scope, elem, attrs) {
elem.on("change", function (e) {
alert("hi");
scope.$eval(attrs.myFiles + "=$files", { $files: e.target.files });
scope.$apply();
sharedDataService.shared = scope;
});
};
});
angular.module("testApp.Controller").directive("xdHref", function () {
return function linkFn(scope, elem, attrs) {
scope.$watch(attrs.xdHref, function (newVal) {
newVal && elem.attr("href", newVal);
});
};
});
//In service.js
testAPIService.postUploadImage = function (file) {
var config = {
headers: {
"Content-Type": undefined,
}
};
var url = urlBase + 'UploadImage';
$http.post(url, file, config).
then(function (response) {
alert(response.data.data);
}).catch(function (response) {
alert( "ERROR " + response.status);
});
In the C# API code:
[HttpPost]
[Route("tests/UploadImage")]
public async Task<HttpResponseMessage> UploadImage()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png", "jpeg" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var filenameOrigin = postedFile.FileName.Substring(0, postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png,.jpeg.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 2 mb.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
string filename = String.Format(#"{0}_{1}_{2}{3}", filenameOrigin, Guid.NewGuid(), DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss"), extension);
var filePath = HostingEnvironment.MapPath("~/Images/" + filename);
postedFile.SaveAs(filePath);
if (!String.IsNullOrEmpty(filePath))
{
dict.Add("filePath", filePath);
}
}
}
var messageSuccess = string.Format("Image Updated Successfully.");
dict.Add("Success", messageSuccess);
return Request.CreateResponse(HttpStatusCode.Created, dict);
}
var res = string.Format("Please Upload a image.");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
catch (Exception ex)
{
var res = string.Format("something went wrong");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
}
In var file, I am getting the uploaded file name, size, image type. In the next line, $http.post, the call is moved to catch, and I am getting error :404 - Please upload a image
What is missed? How to fix this?
Thanks

is it possible to send uploaded file from angularjs to spring controller but by formbean

I have form having text field and file type. I want to send this to controller using form bean. here is my code.following is my js file. from where I'm sending multipart file.
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, uploadUrl, uploadform) {
var fd = new FormData();
fd.append('file', file);
fd.append("jsondata", JSON.stringify(uploadform));
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function () {
})
.error(function () {
});
}
}]);
myApp.controller('myFileUpload', ['$scope', 'fileUpload', function ($scope, fileUpload) {
$scope.uploadFile = function () {
var file = $scope.myFile;
$scope.uploadform = {};
var uploadUrl = "navigation/uploadexcel";
fileUpload.uploadFileToUrl(file, uploadUrl, $scope.uploadform);
};
}]);
and my controller is..I want to map multipart file and textbox value into firmbean first and from that I want to get my file for further process.
#RequestMapping(value = "/uploadexcel", method = RequestMethod.POST)
public #ResponseBody
String upload(#RequestBody EmployeeFormBean fb) {
String res = null;
try {
MultipartFile f = fb.getFile();
System.out.println("-->"+ f.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
my jsp code is as following
<div style="background-color: blanchedalmond">
<div ng-controller = "myFileUpload">
<input type="file" file-model="myFile"/>
<input type="text" name="template" ng-model="uploadform.templateName"/>
<button ng-click="uploadFile()">upload me</button>
</div>
</div>
but m getting error as follow...
415 Unsupported Media Type
59ms
angular...DF52B9C (line 103)
HeadersPostResponseHTMLCookies
"NetworkError: 415 Unsupported Media Type - http://localhost:8080/crmdemo1/navigation/uploadexcel"
how to resolve this issue. I dont want to do it by #resuestparam("file")
is it possible to do this using formbean.. and if yes please tell me how can I do it?
You have a problem in the content type of your request, try to add headers = "content-type=multipart/*" , consumes = "application/json" to #RequestMapping. Beside that (in your service fileUpload) change the headers: {'Content-Type': undefined} to headers: {'Content-Type': application/json}. Hope this will help you

Request with different files in danialfarid angular-file-upload

I used danialfarid angular-file-upload to upload files.
I want to send request with two files and one json string.
Each two files has different params in Server side.
Server side used spring rest.
How can I send?
Here is my angular service.
services.factory('USR008Service', function($resource, $http, $upload) {
return {
insertUSR008FUN01 : function(talent, talentFile, coverImg) {
return $upload.upload({
url: contextRoot + '/insertUSR008FUN01',
fields: {
'USR008REQ02': JSON.stringify(talent),
},
file: coverImg,
fileFormDataName : 'coverImg'
});
}
}
});
Here is my Server Side Controller.
#RequestMapping(value = URIConstant.insertUSR008FUN01, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
public #ResponseBody USR008RES02 insertUSR008FUN01(#RequestParam(value = "talentFile", required = false) MultipartFile talentFile, #RequestParam(value = "USR008REQ02") String jsonData,
#RequestParam(value = "coverImg", required = false) MultipartFile coverImg) {
USR008RES02 result = null;
try {
Gson gson = new GsonBuilder().create();
USR008REQ02 usr008req02 = gson.fromJson(jsonData, USR008REQ02.class);
result = usr008SEV.insertUSR008RES02(usr008req02, talentFile, coverImg);
} catch (SystemException e) {
logger.error("insertUSR008FUN01 function has been failed.");
throw new SystemException("insertUSR008FUN01 function has been failed.", e);
}
return result;
}
This is how I implemented this in my app.
HTML
<label for="uploadDomainFile">Select File</label>
<input type="file" class="form-control" id="uploadDomainFile" ng-model="fileDomain" ng-file-select>
<label for="uploadLegalFile">Select File</label>
<input type="file" id="uploadLegalFile" ng-model="fileLegal" ng-file-select>
JS
//controller
$scope.createDomain = function () {
adminService.createDomain($scope.domain, $scope.fileLegal, $scope.fileDomain);
};
//service
//ommitting irrelevant code
uploadOwlFile(fileLegal, domain.id);
uploadOwlFile(fileDomain, domain.id);
var uploadOwlFile = function(file, domainId) {
if (file && !!file.value) {
$upload.upload({
url: '/api/space/' + domainId + '/owl',
data: { fileType: file.fileType },
file: file.value[0]
})
.progress(function(evt){
console.log('progress: ' + parseInt(100 * evt.loaded / evt.total))
})
.success(function(data, status, headers, config){
console.log('success', 'file: ' + config.file.name + ' successfully uploaded');
return true;
})
.error(function(err, status){
console.log('failure', err);
return false;
})
} else {
return true;
}
};
Returning true or false is based on the status of the file upload.
So, my method involves using two ng-models for the 2 inputs and uploading the file separately.

Resources