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();
}
Related
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
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
I'm trying to upload an object file which contains 2 attributes, a name and a picture using AngularJS. I know that this topic has been treated multiple times but no matter what I read I can't seem to make it work.
I'm using Java Spring for my server and when I try to upload a "Character" (name + picture) through my client I get this error in my server : "Required request body content is missing"...
Here is my code :
.config(function($stateProvider, $httpProvider, $resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
$httpProvider.defaults.transformRequest = function(data) {
if (data === undefined)
return data;
var fd = new FormData();
angular.forEach(data, function(value, key) {
if (value instanceof FileList) {
if (value.length == 1) {
fd.append(key, value[0]);
} else {
angular.forEach(value, function(file, index) {
fd.append(key + '_' + index, file);
});
}
} else {
fd.append(key, value);
}
});
return fd;
}
$httpProvider.defaults.headers.post['Content-Type'] = undefined;
And here is my service :
angular.module('myApp.services', ['ngResource'])
.factory('Character', function($resource) {
return $resource('http://localhost:8080/myApp/character/:id',
{ id: '#id' },
{ update: { method: 'GET', transformRequest: angular.identity, headers: { 'Content-Type': undefined } } }
);
})
.service('popupService', function($window){
this.showPopup = function(message){
return $window.confirm(message);
}
});
And finally this is how I'm using it in my controller :
.controller('CharacterCreateController',function($scope,$state,$stateParams,Character){
$scope.character = new Character();
$scope.addCharacter = function(){
$scope.character.$save(function(){
$state.go('characters');
});
}
})
Could anyone please help me ??? I really don't know what to do and it's my first time trying to upload files using Angular.
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]);
}
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.