Bonjour,
Je souhaite d'envoyer à mon serveur localhost une image séléctionnée depuis l'utilisateur en utilisant AngularJS.
-Code HTML:
<form role="form" enctype="multipart/form-data" name="myForm" ng-submit="uploadfile()">
<label class="control-label">Image:</label>
<input type="file" class="form-control " file-model="Image" >
<button type="submit"> save</button>
</form>
-Code AngularJS;
var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.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]);
});
});
}
};
}]);
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
//fd.append('file', file);
angular.forEach(file, function(file) {
fd.append('file', file);
});
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log("done post");
})
.error(function(data){
console.log("failed to post "+data); //
});
}
}]);
//upload file
$scope.uploadfile = function() {
var file = $scope.Image;
console.dir(file);
var uploadUrl ="http://localhost:8000/auditconfig/images/"+file.name; // la récupération d'une image existe dans ce dossier s'affiche sur l'écran sans probléme
fileUpload.uploadFileToUrl(file, uploadUrl); // affiche toujours "failed to post"
};
Aprés un test de la fonction "uploadfile()", j'obtiens les résultats suivants:
//**console.dir(file);
*File:
lastModified:1490260924299
lastModifiedDate; Thu Mar 23 2017 10:22:04 GMT+0100 (Paris, Madrid)
name:"01.png"
size:1637
type:"image/png"
webkitRelativePath:""
__proto__:File
//**Erreur d'upload**
Failed to load resource: the server responded with a status of 500 (Internal Server Error) :8099/AuditConf/images/01.png
failed to post [object Object]
//** Résultat de l'accés à l'adresse: http://localhost:8000/auditconfig/images/
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Mar 29 01:03:17 CEST 2017
There was an unexpected error (type=Not Found, status=404).
Not Found
Comment je peux régler ce probléme ?
Merci de m'aider pour trouver la bonne solution,
Bonjour,
J'ai résolu le probléme en se basant sur la solution suivante: :)
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.then(function (results) {
console.log("done post "+results);
return results;
}).catch(function(e) {
console.log('failed to post: ', e);
throw e;
})
};
}]);
//upload file
$scope.uploadfile = function() {
var file = $scope.Image;
console.dir(file);
// il faut spécifier le path de l'api et non pas le path de dossier image
var uploadUrl ="http://localhost:8000/auditconfig/Emp/UploadFile";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
Deja pour commencer .success et .error sont deprecié et remplacé par du .then et du .catch.
l'url que tu appel en POST est bonne? pas de fautes de frappes?
Bonjour,
Merci Defy pour ta réponse.
J'ai essayé de changer le code comme tu as dit et j'obtiens la résultat suivant:
//**console.log('failed to post: ', e);
Objectconfig:
Objectdata:FormData
headers:Object
method:"POST"
transformRequest:function identity($)
transformResponse:Array(1)
url:"http://localhost:8000/auditconfig/images/01.png"
__proto__:Object
data: Object
error:
"Internal Server Error"
exception:"java.lang.RuntimeException"
message:"java.io.IOException: UT000036: Connection terminated parsing multipart data"
path:"/auditconfig/images/01.png"
status:500
timestamp:1490773968550
__proto__:Object
//test de l'affichage d'une image à travers l'url de mon application "JEE" :"http://localhost:8000/auditconfig/images/avatar.png"
// l'image "avatar.png" est bien affiché sur le navigateur
j'ai un probléme dans le parsing multipart data.
Comment je peux résoudre çà?
Voilà ce que j'ai dans le fichier log du mon serveur:
2017-03-29 10:57:01.893 DEBUG 10864 --- [ XNIO-2 task-38] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Written [{timestamp=Wed Mar 29 10:57:01 CEST 2017, status=404, error=Not Found, message=Not Found, path=/auditconfig/images/}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@3a0896b3]
2017-03-29 10:57:01.893 DEBUG 10864 --- [ XNIO-2 task-38] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-03-29 10:57:01.893 DEBUG 10864 --- [ XNIO-2 task-38] o.s.web.servlet.DispatcherServlet : Successfully completed request
2017-03-29 10:57:16.380 ERROR 10864 --- [ XNIO-2 task-31] io.undertow.request : UT005023: Exception handling request to /auditconfig/images/01.png
java.lang.RuntimeException: java.io.IOException: UT000036: Connection terminated parsing multipart data
at io.undertow.servlet.spec.HttpServletRequestImpl.parseFormData(HttpServletRequestImpl.java:779) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.spec.HttpServletRequestImpl.getParameter(HttpServletRequestImpl.java:653) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:75) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) ~[spring-boot-actuator-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) ~[undertow-core-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46) ~[undertow-core-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60) ~[undertow-core-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43) ~[undertow-core-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) ~[undertow-core-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) ~[undertow-core-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48) [undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43) [undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104) [undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:211) [undertow-core-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:809) [undertow-core-1.4.11.Final.jar:1.4.11.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_102]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_102]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_102]
Caused by: java.io.IOException: UT000036: Connection terminated parsing multipart data
at io.undertow.server.handlers.form.MultiPartParserDefinition$MultiPartUploadHandler.parseBlocking(MultiPartParserDefinition.java:218) ~[undertow-core-1.4.11.Final.jar:1.4.11.Final]
at io.undertow.servlet.spec.HttpServletRequestImpl.parseFormData(HttpServletRequestImpl.java:777) ~[undertow-servlet-1.4.11.Final.jar:1.4.11.Final]
J'ai modifier la fonction et le content type:
this.uploadFileToUrl = function(file, uploadUrl){
var data = new FormData();
data.append('file', file);
return $http.post(uploadUrl, data, {
transformRequest: angular.identity,
//headers: { 'Content-Type': undefined }
hearders:{'Content-Type':'multipart/form-data'}
}).then(function (results) {
console.log("done post "+results);
return results;
}).catch(function(e) {
console.log('failed to post: ', e);
throw e;
})
};
Voilà ce que j'obtiens:
//Failed to load resource: the server responded with a status of 404 (Not Found) --> :8000/auditconf/images/01.png
Object
hearders:Object
Content-Type:"multipart/form-data"
__proto__:Object
method:"POST"
config:Object
data:FormData
headers:Object
Accept:"application/json, text/plain, */*"
Content-Type:undefined
__proto__:Object
method:"POST"
transformRequest:function identity($)
transformResponse:Array(1)
url:"http://localhost:8000/auditconfig/images//01.jpeg"
__proto__:Object
data:Object
error:"Not Found"
message:"Not Found"
path:"/auditconfig/images/01.jpeg"
status:404
timestamp:1490784252522
__proto__:Object
headers:function (name)
status:404
statusText:"Not Found"
__proto__:Object
Vraiment j'ai pas compris pourquoi s'affiche le probléme