Angularjs file upload not working - java

Java Controller class:
#RequestMapping(value = "/upload" , method = RequestMethod.POST , consumes="multipart/form-data")
public void upload(#RequestParam MultipartFile file1) {
System.out.println("*****"+ file1);
}
html file:
<input id="file-0a" class="file" type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
angular js:
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var fd = new FormData();
fd.append('file', file);
var resource = /upload;
$http.post(resource, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function(){ }).error(function(){ });
}
And this is the error I dont understand in the server log:
INFO: Server startup in 38138 ms
Feb 14, 2015 11:45:17 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet dispatcher threw exception
java.lang.IllegalStateException: Cannot forward after response has been committed
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:348)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:338)
at org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler.handleRequest(DefaultServletHttpRequestHandler.java:122)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:467)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:342)
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:434)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:205)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Feb 14, 2015 11:45:17 PM org.apache.catalina.core.StandardHostValve custom
SEVERE: Exception Processing ErrorPage[errorCode=0, location=/error.html]
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Cannot forward after response has been committed
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)

Try the following. It is working fine for me.
HTML You should have
<input id="file-0a" class="file" type="file" file-model="myFile" name="myFile" />
<button ng-click="uploadFile()">upload me</button>
Note the name of the input.
Then in JS controller method you should have
$scope.uploadFile = function(){
var formData=new FormData();
formData.append("file",myFile.files[0]); //myFile.files[0] will take the file and append in formData since the name is myFile.
$http({
method: 'POST',
url: '/upload', // The URL to Post.
headers: {'Content-Type': undefined}, // Set the Content-Type to undefined always.
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
}).success(function(data, status) {
})
.error(function(data, status) {
});
}
Now in Your Java Controller class
#RequestMapping(value = "/upload" , method = RequestMethod.POST)
public void upload(HttpServletRequest request) {
//org.springframework.web.multipart.MultipartHttpServletRequest
MultipartHttpServletRequest mRequest;
mRequest = (MultipartHttpServletRequest) request;
Iterator<String> itr = mRequest.getFileNames();
while (itr.hasNext()) {
//org.springframework.web.multipart.MultipartFile
MultipartFile mFile = mRequest.getFile(itr.next());
String fileName = mFile.getOriginalFilename();
System.out.println("*****"+ fileName);
//To copy the file to a specific location in machine.
File file = new File('path/to/new/location');
FileCopyUtils.copy(mFile.getBytes(), file); //This will copy the file to the specific location.
}
}
Hope this works for You. And do Exception Handling also.

Related

Spring - AngularJS - File Upload - org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

I am facing the below Exception while uploading a file from angular to my Java Spring MVC web application server
<form role="form" name="attachForm" class="form-horizontal" >
<div class="form-group">
<input class="col-xs-12" id="uploadFile" type="file" name="uploadFile" file-model ="myFile" ng-disable="closeHidden" required />
</div>
</div>
</form>
In my AngularJs
var saveFileURL = "caseapi/saveFile";
var fd = new FormData();
fd.append('file', scope.myFile);
return $http.post(saveFileURL,fd,{
transformRequest: angular.identity,
headers: {
"Content-Type": undefined
}
});
My Directive
(function() {
define([ 'appModule'], function(app) {
app.directive('fileModel', [ '$parse', function($parse) {
return {
restrict : 'A',
link : function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
console.log("fileModelDir");
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
});
});
}
};
} ]);
});
}).call(this);
Server-side
#RequestMapping(value = "/saveFile", method = RequestMethod.POST)
public void saveFile( MultipartFile fd, HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("SAVE FILE fd : " +fd);
logger.info("File name :" + fd.getName());
try
{
/** TODO: Implement file handling **/
logger.info("saveDraft serviceResponse: ");
handleResponse(response, serviceResponse);
logger.info("Exitting saveDraft");
} catch (Exception ex) {
logger.error("Error while calling service: ",ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
Below is the Error
SEVERE: Servlet.service() for servlet [GVEClientExperience] in context
with path [] threw exception [Request processing failed; nested
exception is org.springframework.web.multipart.MultipartException:
Could not parse multipart servlet request; nested exception is
org.apache.commons.fileupload.FileUploadException: the request was
rejected because no multipart boundary was found] with root cause
org.apache.commons.fileupload.FileUploadException: the request was
rejected because no multipart boundary was found
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.
<init>(FileUploadBase.java:990)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:310)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:334)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:139)
at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1041)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:887)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:851)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.ebaysf.web.cors.CORSFilter.handleSimpleCORS(CORSFilter.java:303)
at org.ebaysf.web.cors.CORSFilter.doFilter(CORSFilter.java:161)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:615)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1770)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1729)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I have as well refered to this post Spring MVC - AngularJS - File Upload - org.apache.commons.fileupload.FileUploadException
but it wasnt of help. I am new to Angular. Would like to understand whats wrong here?
Add the enctype property to your FORM tag.
<form enctype="multipart/form-data">
Late but could help somebody:
Use ngFileUpload, like this:
$scope.uploadFile = function (file, param1, param2)
{
var params ={'param1': param1, 'param2': param2};
Upload.upload({
url: 'http://localhost/uploadFile',
data: {file:file},
params: params
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
}).catch (function onError(data){
console.error("Upload pic exception");
console.error(JSON.stringify(data));
});;
};
You can also put the parameters inside the data variable.
It seems to be a problem on your request. Try to do this.
return $http.post(saveFileURL,fd,{
transformRequest: angular.identity,
headers: {
"Content-Type": "multipart/form"
}
});
Here is W3C specification mentioning it
in which one or more different sets of data are combined in a single body, a "multipart" Content-Type field must appear in the entity's header.
https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
you need to specify the data type to consume in your controller and add request param with the key of your file
#RequestMapping(value = "/saveFile", method = RequestMethod.POST, consumes = {"multipart/form-data"})
public void saveFile(#RequestParam(name="fd") MultipartFile fd, HttpServletRequest request, HttpServletResponse response) throws Exception {
and no need for contentType:undefined
return $http.post(saveFileURL,fd,{
transformRequest: angular.identity,
});
and add the encrypt type in your form ad daddygames mentioned
enctype="multipart/form-data">
We have managed to deal with such a requirement using simple yet powerful third-party directive angular-upload. Use is pretty straightforward and simple. More details you can find in documentation.
In HTML page:
<div
class="btn btn-primary btn-upload"
upload-button
url="/upload"
on-success="onSuccess(response)">Upload</div>
In Angular Controller:
$scope.onSuccess = function(response) {
// Do something
};
In Spring Controller:
#RequestMapping(value = "upload", method = RequestMethod.POST)
public void uploadAccessFile(#RequestParam("file") MultipartFile file) {
// Do something with file
}
And finally in your Configuration:
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
return resolver;
}
Adding "Content-Type": undefined in the request and data type to consumes = {"multipart/form-data"})

ControllerAdvice not handling exception

I have a spring boot 1.3.3 application. I have a rest controller that throws an exception in certain situations. The exceptions are being thrown and the message printed but the ControllerAdvice class is not being fired. Here's my relevant files:
TestController.java
#Controller
public class TestController {
// RESTful method
#RequestMapping(
value = "/test",
method = RequestMethod.POST,
consumes = "application/json",
produces = "application/json")
#ResponseBody
public JsonNode fooRestTest(#RequestHeader HttpHeaders header,
#RequestBody String payload) {
ControllerUtil.validateHeaders(header);
return null;
}
}
ControllerUtil.java
public class ControllerUtil {
public static void validateHeaders(HttpHeaders headers) {
if(headers.get("test-field") == null) {
throw new InvalidHeaderException("Invalid test-field in header");
}
}
}
InvalidHeaderException.java
public class InvalidHeaderException extends RuntimeException {
public InvalidHeaderException(String message) {
super(message);
}
public InvalidHeaderException(String message, Throwable cause) {
super(message, cause);
}
}
AppErrorController.java
#ControllerAdvice
#EnableWebMvc
public class AppErrorController {
#ExceptionHandler(InvalidHeaderException.class)
public ModelAndView handleHeaderError(HttpServletRequest req, Exception ex) {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.addObject("timestamp", LocalDateTime.now());
mav.addObject("status", 400);
return mav;
}
}
web.xml
<web-app id="RBGApp" version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>FooTester</display-name>
<servlet>
<servlet-name>Foo_Test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Mappings -->
<servlet-mapping>
<servlet-name>Foo_Test</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
MvcConfiguration.java
#Configuration
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
#Autowired
ServletContext servletContext;
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public ViewResolver getJspViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/jsp/views/");
resolver.setSuffix(".jsp");
resolver.setOrder(1);
return resolver;
}
}
I tested this with a request from postman and it throws the exception and prints out the line:
Invalid test-field in header
But the code never goes into the AppErrorController at all. So none of the other values like timestamp are populated. Any idea what i'm doing wrong here?
Edit 1:
This is what postman spits out as the response:
<html>
<head>
<title>Apache Tomcat/7.0.62 - Error report</title>
<style>
<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}-->
</style>
</head>
<body>
<h1>HTTP Status 500 - Invalid test-field in header</h1>
<HR size="1" noshade="noshade">
<p>
<b>type</b> Exception report
</p>
<p>
<b>message</b>
<u>Invalid test-field in header</u>
</p>
<p>
<b>description</b>
<u>The server encountered an internal error that prevented it from fulfilling this request.</u>
</p>
<p>
<b>exception</b>
<pre>controllers.exceptions.InvalidHeaderException: Invalid test-field in header
controllers.util.ControllerUtil.validateHeaders(ControllerUtil.java:12)
controllers.TestController.fooRestTest(TestController.java:77)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:120)
org.springframework.boot.context.web.ErrorPageFilter.access$000(ErrorPageFilter.java:61)
org.springframework.boot.context.web.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:95)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:113)
</pre>
</p>
<p>
<b>note</b>
<u>The full stack trace of the root cause is available in the Apache Tomcat/7.0.62 logs.</u>
</p>
<HR size="1" noshade="noshade">
<h3>Apache Tomcat/7.0.62</h3>
</body>
</html>
Edit 2: Console output when making the postman request
09:08:14.373 [http-bio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'Foo_Test' processing POST request for [/TEST]
09:08:14.381 [http-bio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /test
09:08:14.390 [http-bio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public com.fasterxml.jackson.databind.JsonNode controllers.AlertController.getAlertsForRest(org.springframework.http.HttpHeaders,java.lang.String)]
09:08:14.390 [http-bio-8080-exec-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'alertController'
09:08:14.426 [http-bio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor - Read [class java.lang.String] as "application/json" with [org.springframework.http.converter.StringHttpMessageConverter#4732b26d]
09:08:14.436 [http-bio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Resolving exception from handler [public com.fasterxml.jackson.databind.JsonNode controllers.AlertController.getAlertsForRest(org.springframework.http.HttpHeaders,java.lang.String)]: controllers.exceptions.InvalidHeaderException: Invalid test-field in header
09:08:14.439 [http-bio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [public com.fasterxml.jackson.databind.JsonNode controllers.AlertController.getAlertsForRest(org.springframework.http.HttpHeaders,java.lang.String)]: controllers.exceptions.InvalidHeaderException: Invalid test-field in header
09:08:14.439 [http-bio-8080-exec-1] DEBUG org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [public com.fasterxml.jackson.databind.JsonNode controllers.AlertController.getAlertsForRest(org.springframework.http.HttpHeaders,java.lang.String)]: controllers.exceptions.InvalidHeaderException: Invalid test-field in header
09:08:14.443 [http-bio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Could not complete request
controllers.exceptions.InvalidHeaderException: Invalid test-field in header
controllers.util.ControllerUtil.validateHeaders(ControllerUtil.java:12)
controllers.TestController.fooRestTest(TestController.java:77)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:871)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:120)
at org.springframework.boot.context.web.ErrorPageFilter.access$000(ErrorPageFilter.java:61)
at org.springframework.boot.context.web.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:95)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:113)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Do you have messages like java.lang.IllegalStateException: No suitable resolver for argument in your log files?
Try to use same exception type at handleHeaderError method argument: InvalidHeaderException instead of Exception. Like this:
#ControllerAdvice
#EnableWebMvc
public class AppErrorController {
#ExceptionHandler(InvalidHeaderException.class)
public ModelAndView handleHeaderError(HttpServletRequest req, InvalidHeaderException ex) {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.addObject("timestamp", LocalDateTime.now());
mav.addObject("status", 400);
return mav;
}
}
May be there is some other handler that is Handling this request(from first 5 lines of console output). That might be in any of the jars that are in the build path of your project.
We need to set priority of your handler as Highest, so control comes here first.
I think adding #Order(Ordered.HIGHEST_PRECEDENCE) after #EnableWebMvc might solve the problem.
#ControllerAdvice
#EnableWebMvc
#Order(Ordered.HIGHEST_PRECEDENCE)
public class AppErrorController {
#ExceptionHandler(InvalidHeaderException.class)
public ModelAndView handleHeaderError(HttpServletRequest req, InvalidHeaderException ex) {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.addObject("timestamp", LocalDateTime.now());
mav.addObject("status", 400);
return mav;
}
Also if it doesn't work try changing InvalidHeaderException.class to Exception.class (Regardless of what exception it is control would come here). Also debugging would be helpful in your case.

J2EE Jersey File Upload - input is always null

I try to create a restful service that uploads a file. I followed the steps of:
http://examples.javacodegeeks.com/enterprise-java/rest/jersey/jersey-file-upload-example/
http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/
But, when I upload a file (for example, a .pdf), the input FormDataMultiPart is always NULL and I don´t understand why. I use the libs "jersey-multipart" and "jersey-core". My code:
Restful service:
#Path("/reservation")
public class ReservationWs {
/** The Constant log. */
private static final Logger LOGGER = LoggerFactory.getLogger(ReservationWs.class.getName());
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://opt/share/reservation/";
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = SERVER_UPLOAD_LOCATION_FOLDER
+ fileDetail.getFileName();
// save it
saveFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
#POST
#Path("/upload2")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile2(FormDataMultiPart form) {
FormDataBodyPart filePart = form.getField("file");
ContentDisposition headerOfFilePart = filePart.getContentDisposition();
InputStream fileInputStream = filePart.getValueAs(InputStream.class);
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + headerOfFilePart.getFileName();
// save the file to the server
saveFile(fileInputStream, filePath);
String output = "File saved to server location using FormDataMultiPart : " + filePath;
System.out.println(output);
return Response.status(200).entity(output).build();
}
}
My client:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Page</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="reservation/upload" method="post" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="55" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
When I try to call to "upload", the input is null and the error logs:
GRAVE: El Servlet.service() para el servlet [rest_1288520529] en el
contexto con ruta [/checking] lanzó la excepción [Error processing
webservice request] con causa raíz java.lang.NullPointerException at
com.checking.reservation.ws.ReservationWs.uploadFile(ReservationWs.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.apache.openejb.server.cxf.rs.PojoInvoker.performInvocation(PojoInvoker.java:43)
at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:165)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:89) at
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:57)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:93)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240)
at
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.onMessage(CxfRsHttpListener.java:187)
at
org.apache.openejb.server.rest.RsServlet.service(RsServlet.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:198)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:176)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
When I try to call to "upload2", the input is null and the error logs:
sep 11, 2015 9:12:21 AM org.apache.catalina.core.StandardWrapperValve
invoke GRAVE: El Servlet.service() para el servlet [rest_348842263] en
el contexto con ruta [/checking] lanzó la excepción [Error processing
webservice request] con causa raíz java.lang.NullPointerException at
com.checking.reservation.ws.ReservationWs.uploadFile2(ReservationWs.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.apache.openejb.server.cxf.rs.PojoInvoker.performInvocation(PojoInvoker.java:43)
at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:165)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:89) at
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:57)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:93)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240)
at
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.onMessage(CxfRsHttpListener.java:187)
at
org.apache.openejb.server.rest.RsServlet.service(RsServlet.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:198)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:176)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Any idea?
I found a not good solution for now.
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(#FormDataParam("file") InputStream file, #FormDataParam("file") FormDataContentDisposition fileDetail, #QueryParam("fileName") String fileName){
...
...
String uploadedFileLocation = SERVER_UPLOAD_LOCATION_FOLDER+ fileName;//fileDetail.getFileName();
// save it
saveFile(file, uploadedFileLocation);
...
//Logic of the service.
...
//Delete file from local.
}
private void saveFile(InputStream uploadedInputStream, String serverLocation) throws IOException {
OutputStream outpuStream=null;
try {
outpuStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch( IOException e){
LOGGER.debug("[UploadWs - saveFile] - error: "+e);
} finally{
if(outpuStream!=null){
outpuStream.close();
}
}
}
"fileDetail" is always null and I don´t know why (if anyone knows the solution, say it) so I add the parameter "fileName" (name of the file) that the client send me. I build the location, I save the file in local, the logic of the service is executed (in my case, I send an email with this file) and I delete the file from local.
It's not a good solution because I add an unnecesarry parameter and I save the file in local.

Spring MVC - Get non-mulitpart form/data in Multipart HTTP Post

Form my client application (AngularJS), I am uploading a file and some other data as FormData.
var formData=new FormData();
formData.append("file",file.files[0]); //files
formData.append("docData", angular.toJson($scope.docdata)); //invoice
Value of angular.toJson($scope.docdata) is like {"configuration":20,"title":"invoicedata"}
This is my HTTP post
$http({
method: 'POST',
url: uploadurl,
headers: {'Content-Type': false},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
})
.success(function(data, status) {
alert("Error");
})
.error(function(data, status) {
alert("Error");
});
The request is getting in my Spring MVC controller and I am able to process with the file. But the other data (docData), I am not able to get.
Here is my UploadController.java
#Controller
public class UploadController {
#RequestMapping(value="/newDocument", method = RequestMethod.POST)
public void UploadFile(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest mRequest=(MultipartHttpServletRequest)request;
Iterator<String> itr=mRequest.getFileNames();
while(itr.hasNext()){
MultipartFile file=mRequest.getFile(itr.next());
String fileName=file.getOriginalFilename();
try {
File newFile = new File("/home/myHome/file-uploaded/"+fileName);
// if the directory does not exist, create it
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
FileCopyUtils.copy(file.getBytes(), newFile);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
Enumeration<String> parametrs = request.getParameterNames();
while(parametrs.hasMoreElements()) {
String param=parametrs.nextElement();
System.out.println("Param : " + param);
Object object=request.getAttribute(param);
System.out.println("Param Instance" + object.getClass().getName());
}
}
}
The first part is working perfectly. (Copying file to the directory). But the second part giving me an exception. First it prints the value of param which is docData the one I send form client app in FormData. Then it throws the exception
java.lang.NullPointerException
at com.serverapp.demoapp.web.UploadController.UploadFile(UploadController.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
Line 63 refers to System.out.println("Param Instance" + object.getClass().getName());
which means the object is null
How to get the values?
When you use multipart then your form fields are included in request Stream. So you have to check whether they are form fields or not.
This is what I use in a servlet, you can make appropriate changes in it to work in Spring-MVC.
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (item.isFormField()) //your code for getting form fields
{
String name = item.getFieldName();
String value = item.getString();
System.out.println(name+value);
}
if (!item.isFormField())
{
//your code for getting multipart
}
}
}

Multipart Http Request

How can i initialized Multipart request..? I am uploading file using multipart/form-data content type but i can't get multipart request in my controller.So how can i get multipart request in my controller ..
Thanks in Advance.
I am getting error like this..
Jun 13, 2012 2:01:05 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/Login] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Multipart request not initialized] with root cause
java.lang.IllegalStateException: Multipart request not initialized
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.initializeMultipart(AbstractMultipartHttpServletRequest.java:107)
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultipartFiles(AbstractMultipartHttpServletRequest.java:97)
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getFile(AbstractMultipartHttpServletRequest.java:60)
at com.mpm.common.controller.FileUploadController.create(FileUploadController.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:585)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:279)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
And my JSP code is :
<body>
<h1>Please upload a file</h1>
<form method="post" action="upload.action" enctype="multipart/form-data">
<input type="text" name="name"/></br>
<input type="file" name="file"/></br>
<input type="submit"/>
</form>
</body>
and my servlet-context.xml code is :
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
</bean>
<bean id="fileUploadController" class="com.mpm.common.controller.FileUploadController" ></bean>
You seem to use Spring. In that case, I usually manage multipart requests like this:
#RequestMapping("/url")
public String method(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// do stuff with multipartRequest
return "/jsp";
}
You simply need to cast your HttpServletRequest request.
public void upload(HttpServletRequest request) {
File up = new File("C:\\temp"); // path where u need to upload
// Create object of MultipartRequest to upload file
MultipartRequest m;
try {
m = new MultipartRequest(request, up.toString());
Enumeration files = m.getFileNames();
// Get the files to be uploaded from enumeration
while (files.hasMoreElements()) {
String upload = (String) files.nextElement();
filename = m.getFilesystemName(upload);
// out.println("<br/><br/><br/><br/>");
}
} catch (IOException e) {
System.out.println("Error in Uploading files...");
}
xsdName = filename.substring(0, filename.lastIndexOf('.'));
}
it was my code to do the same in servlet. Hope it helps.

Categories