how to hide this button during convert of html page to pdf using iText in Spring Boot and Thymleaf - spring

I am facing problem during pdf generation when I am converting html page into pdf that time button is also showing, but requirement is button should not be show but button should be on same page and after click PDF should be generate. I am using iText for Pdf generation. I am using Thymeleaf and Spring Boot.
I have used this code for pdf generation.
#RequestMapping("download-pdf/{refno}")
public ResponseEntity<?> getPDF(HttpServletRequest request, HttpServletResponse response,#PathVariable("refno") Long refno) throws IOException, IllegalAccessException, InvocationTargetException {
complaintDto = complaintRepo.findById(refno).orElse(null);
complaintPdfBean = pdfService.getComplaintInfo(complaintDto);
WebContext context = new WebContext(request, response, servletContext);
context.setVariable("complaintPdfBean", complaintPdfBean);
String grievanceHtml = templateEngine.process("complant-privew", context);
ByteArrayOutputStream target = new ByteArrayOutputStream();
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.setBaseUri("http://localhost:8080");
HtmlConverter.convertToPdf(grievanceHtml, target, converterProperties);
byte[] bytes = target.toByteArray();
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=grievance.pdf")
.contentType(MediaType.APPLICATION_PDF).body(bytes);
}
I am using this maven dependency in pom.xml file:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.0</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>2.0.0</version>
</dependency>
<!-- pdf dependency -->

Wrap your button with a <th:block> and an th:unless statement:
<th:block th:unless="${isPdfExport}">
...
</th:block>
Set the isPdfExport context variable to true just before the PDF generation.

Related

How to generate static files from a Spring Thymeleaf project?

I have a website that was built using Spring Thymeleaf, and I'd like to generate the files, such as an index.html, css, and js files, in a flat directory so that I can serve the compiled/transpiled files from an AWS S3 bucket. The project is a Gradle project. How do I do this? Thank you in advance.
You can run Thymeleaf as a Java program (rather than on a server) and generate HTML files like this:
public class Application {
public static void main(String... args) {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(new AnnotationConfigApplicationContext());
resolver.setPrefix("classpath:/html/");
resolver.setSuffix(".html");
resolver.setCharacterEncoding("UTF-8");
resolver.setTemplateMode(TemplateMode.HTML);
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(resolver);
Context context = new Context();
String html = engine.process("index", context);
System.out.println(html);
}
}
Simply replace the System.out.println(html); with saving the html variable to a file. Then you just have to read your directory for all the files you want to interpret and run the code for everything.
This will not work for forms -- but I'm assuming you don't need any actually dynamic content if you are trying to compile your Thymeleaf to static html.
You will also have to include the right dependencies. I use these:
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>

Why does java Spring return no such method exception for aws sdk while initializing the awsS3Client

I'm trying to upload dynamic objects into the s3 bucket in my web application.
But struggling with no such method error during initializing the AWS3Client.
Initially, the input is a multipart image saving it into a local machine and then using it for uploading it into the s3 bucket.
During uploading the No such method exception occurs as shown in the first image.
Exception snapshot during client initialization
Also, specified the amazon dependency used into pom in the second picture.
pom-Amazon_dependency
following is the code used for initiating s3client into the application.
Map<String, String> s3Credentials = ((FSRepositoryServiceImpl) fsRepositoryService).getS3Credentials();
AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.AP_SOUTH_1).withCredentials(
new AWSStaticCredentialsProvider(new BasicAWSCredentials(s3Credentials.get("accessKeyId"),
s3Credentials.get("secretAccessKey"))))
.build();
Here are some more details about the issue
Pom dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.13.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-s3 -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.12.150</version>
</dependency>
Code to upload object into s3 bucket:
//Save temporary document in file format for uploading to s3
Map<String, String> s3ObjectDetails = fsRepositoryService.saveTempDocumentforS3Reference(
basePatientDocumentsRepoPath, docContents, ext, originalImgFileName);
//Credentials for aws account
Map<String, String> s3Credentials = ((FSRepositoryServiceImpl) fsRepositoryService).getS3Credentials();
AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.AP_SOUTH_1).withCredentials(
new AWSStaticCredentialsProvider(new BasicAWSCredentials(s3Credentials.get(<accessKeyId>),
s3Credentials.get(<secretAccessKey>))))
.build();
//bucket details on the aws cloud
Map<String, String> bucketDetails = ((FSRepositoryServiceImpl) fsRepositoryService).getBucketDetails(
/* used this for dynamic key name for bucket */s3ObjectDetails.get(<document Name>));
String uploadingPath = bucketDetails.get(<filePath>) + "/" + patientId + "/";
uploadingPath = uploadingPath.replace("//", "/");
String fileToUpload = s3ObjectDetails.get(<Pathofthedocument>);
PutObjectRequest objectRequest = new PutObjectRequest(bucketDetails.get(bucket),
uploadingPath + bucketDetails.get(<key>), <fileToUpload>);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType("plain/text");
metadata.addUserMetadata(<key Name>, bucketDetails.get(key));
objectRequest.setMetadata(metadata);
PutObjectResult uploadImagetoS3 = s3.putObject(objectRequest);
Error statement:
02:54,190 INFO :
Saving Doc 5f5ab725-0403-4554-b62c-674130c9a8f2-1643628704942 under: /data/ihealwell/patients/ImagePrescription/20808/
Jan 31, 2022 5:07:27 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [api-dispatcher] in context with path [/IHW] threw exception [Handler processing failed; nested exception is java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.ObjectMapper.enable([Lcom/fasterxml/jackson/core/JsonParser$Feature;)Lcom/fasterxml/jackson/databind/ObjectMapper;] with root cause
java.lang.NoSuchMethodError: com.fasterxml.jackson.databind.ObjectMapper.enable([Lcom/fasterxml/jackson/core/JsonParser$Feature;)Lcom/fasterxml/jackson/databind/ObjectMapper;
at com.amazonaws.partitions.PartitionsLoader.(PartitionsLoader.java:54)
at com.amazonaws.regions.RegionMetadataFactory.create(RegionMetadataFactory.java:30)
at com.amazonaws.regions.RegionUtils.initialize(RegionUtils.java:64)
at com.amazonaws.regions.RegionUtils.getRegionMetadata(RegionUtils.java:52)
at com.amazonaws.regions.RegionUtils.getRegion(RegionUtils.java:106)
at com.amazonaws.client.builder.AwsClientBuilder.getRegionObject(AwsClientBuilder.java:256)
at com.amazonaws.client.builder.AwsClientBuilder.withRegion(AwsClientBuilder.java:245)
at com.amazonaws.client.builder.AwsClientBuilder.withRegion(AwsClientBuilder.java:232)
at com.indohealth.ihealwell.web.rest.controller.PatientResourceController.saveOnS3Resource(PatientResourceController.java:1932)
at com.indohealth.ihealwell.web.rest.controller.PatientResourceController.saveDocumentOnGlobalResource(PatientResourceController.java:1891)
at com.indohealth.ihealwell.web.rest.controller.DocumentResourceController.updateDocumentbyPatient(DocumentResourceController.java:288)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)

Unstable Primefaces fileupload listener call

Having a Spring Boot project working with JDK11, Primefaces 8.0, Spring Boot 2.3.0.
deploying it on tomcat 9.0.35. In some deployments my fileupload component is able to trigger the listener method well. In some other, it can't trigger it leaving no error message or log.
I have tried some restarts producing every time same results (fail to upload) with the same build. But despite having not touched the source, another build can make it work.
On another test, I have built & deployed 4-5 times the project with exactly same source code, seeing upload is working in all of them. And for a last test, I just added a space character after a java statement's ';' to change the binary and rebuilt, redeployed and noticed file upload not working.
I can't find out why the behaviour is not stable.
I am stuck and have no idea how to debug it, identify the problem. Any suggestion will be welcomed
At pom.xml having:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.20</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.20</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>8.0</version>
</dependency>
<dependency>
<groupId>com.google.code</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.0</version>
</dependency>
FileUpload component on page:
<h:form id="bulkDataInsertForm" enctype="multipart/form-data">
.
.
<p:fileUpload id="datafileuploader"
listener="#{bulkDataInsertBean.handleFileUpload}"
uploadLabel="upload file"
cancelLabel="cancel"
label="choose file"
update=":bulkDataInsertForm:bulkDataInsertgrowl :bulkDataInsertForm:listFileUploadPanel :bulkDataInsertForm:errorText"
allowTypes="/(\.|\/)(xlsx)$/"
sizeLimit="10485760"
multiple="false"
invalidFileMessage="file type error"
mode="advanced" dragDropSupport="true"
ajax="true">
</p:fileUpload>
.
.
</h:form>
I have <h:head> in parent page as told here: How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable.
And ServletInitializer:
#EnableEncryptableProperties
#SpringBootApplication
#ComponentScan({ "com.myapp" })
public class WebApplication extends SpringBootServletInitializer {
#Bean
public ServletRegistrationBean kaptchaServletRegistration() {
ServletRegistrationBean bean = new ServletRegistrationBean(new KaptchaServlet(), "/kaptcha.jpg");
return bean;
}
#Bean
public ServletRegistrationBean facesServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean<>(new FacesServlet(), "*.xhtml");
registration.setLoadOnStartup(1);
return registration;
}
#Bean
public ServletContextInitializer servletContextInitializer() {
return servletContext -> {
servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());
servletContext.setInitParameter("primefaces.THEME", "blitzer");
servletContext.setInitParameter("primefaces.CLIENT_SIDE_VALIDATION", Boolean.TRUE.toString());
servletContext.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", Boolean.TRUE.toString());
servletContext.setInitParameter("primefaces.FONT_AWESOME", Boolean.TRUE.toString());
servletContext.setInitParameter("javax.faces.ENABLE_CDI_RESOLVER_CHAIN", Boolean.TRUE.toString());
};
#Bean
public ServletListenerRegistrationBean<ConfigureListener> jsfConfigureListener() {
return new ServletListenerRegistrationBean<>(new ConfigureListener());
}
//for setting fileUploadFilter to in front of filterChain - so uploaded file not consumed by other filter
#Bean
public FilterRegistrationBean primeFacesFileUploadFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean(new org.primefaces.webapp.filter.FileUploadFilter(), facesServletRegistration());
registration.addUrlPatterns("/*");
registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD);
registration.setName("primeFacesFileUploadFilter");
registration.setOrder(1);
return registration;
}
}
Note: On some forums, I have read fileupload filter order can be changed, so some other filters may consume the file stream being uploaded, leaving fileupload filter with no input.
It must also accept Forwarded requests. So I added "primeFacesFileUploadFilter" shown above, but it did not help:
This is the order of filterchain during ServletContextInitializer after added the code:
Filter names at FilterChain by order: [requestContextFilter, Tomcat WebSocket (JSR356) Filter, errorPageFilter, primeFacesFileUploadFilter, characterEncodingFilter, springSecurityFilterChain, formContentFilter]
Specifying
servletContext.setInitParameter("primefaces.UPLOADER", "native");
at servletContextInitializer resulted in sometimes successful and sometimes failing(listener untriggered) fileuploads.
But after specifiying:
servletContext.setInitParameter("primefaces.UPLOADER", "commons");
instead of "native", I did nearly 10 builds, deploys, tests in which all fileuploads triggered properly. Of course I can't still guarantee its the absolute solution but
its highly likely.

Object distortion while passing from REST service to Spring app

I've got strange problem and I hope you will to help me to solve it.
I try to pass list of objects, where each object contains LocalDate parameter (JodaTime library) from test service to my controller.
This is method from my service. It returns list of objects. Look at the dates printed out in the loop.
#RequestMapping("/getListaRecept")
#ResponseBody
public ListaRecept sendAnswer(){
ListaRecept listaReceptFiltered = prescriptionCreator.createListaRecept();
for(Recepta r : listaReceptFiltered.getListaRecept()){
System.out.println(r.toString());
}
return listaReceptFiltered;
}
Dates are correct
Recepta{id=3, nazwa='nurofen', status=NOT_REALIZED, date=2017-07-27}
Recepta{id=1, nazwa='ibuprom', status=ANNULED, date=2014-12-25}
Recepta{id=2, nazwa='apap', status=REALIZED, date=2016-08-18}
And now I'm invoking this method from my SpringBoot app using restTemplate. And then received list is printed out
private final RestTemplate restTemplate;
public SgrService2(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
this.restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-16")));
}
public ListaRecept getList() {
for(Recepta r : this.restTemplate.getForObject("http://localhost:8090/getListaRecept",
ListaRecept.class).getListaRecept()){
System.out.println(r.toString());
}
return this.restTemplate.getForObject("http://localhost:8090/getListaRecept",
ListaRecept.class);
}
As you can see all dates were replaced with current date :/
Recepta{id=3, nazwa='nurofen', status=NOT_REALIZED, date=2017-09-30}
Recepta{id=1, nazwa='ibuprom', status=ANNULED, date=2017-09-30}
Recepta{id=2, nazwa='apap', status=REALIZED, date=2017-09-30}
I have no idea what is going on...
Here you have pom dependencies
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.1</version>
</dependency>
Thank you in advance for your help
It seems to me that you are using the wrong jackson module, instead of jsr310 (which I guess is for Java 8 date types), try using the artifact jackson-datatype-joda and register the module JodaModule.

Spring MVC file upload - Unable to process parts as no multi-part configuration has been provided

So I'm a newbie to Spring and I'm trying to get file upload working for my project (I'm using Spring Tool Suite btw.) and when submitting a form all I'm getting is:
HTTP Status 500 - Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
Stack trace from browser:
type Exception report
message Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:100)
org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.(StandardMultipartHttpServletRequest.java:78)
org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:75)
org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:108)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106)
root cause
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
org.apache.catalina.connector.Request.parseParts(Request.java:2676)
org.apache.catalina.connector.Request.getParts(Request.java:2643)
org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1083)
org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:85)
org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.(StandardMultipartHttpServletRequest.java:78)
org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:75)
org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:108)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:106)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.27 logs.
This is the form tag in jsp:
<form:form class="form-horizontal" role="form" method="post"
action="newArtist.html" modelAttribute="artist" enctype="multipart/form-data">
Input part:
<div class="form-group">
<div class="col-lg-3">
<label for="photo">Artist photo:</label>
<form:input type="file" id="photo" path="photo"></form:input>
</div>
</div>
Photo is stored in this field in Artist object:
#Lob
private byte[] photo;
Controller mapping methods:
#RequestMapping(value = "/newArtist", method = RequestMethod.GET)
public String showAddArtistForm(Model model)
{
model.addAttribute("artist", new Artist());
return "newArtist";
}
#RequestMapping(value = "/newArtist", method = RequestMethod.POST)
public String addArtist(#ModelAttribute("artist") #Valid Artist artist, BindingResult result,
#RequestParam("photo") MultipartFile photo) throws IOException
{
if (result.hasErrors())
return "newArtist";
if(photo.getBytes() != null)
artist.setPhoto(photo.getBytes());
artistService.addArtist(artist);
return "redirect:artists.html";
}
Multipart resolver configuration in servlet-context.xml:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
Filters in web.xml:
<filter>
<filter-name>MultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>MultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Dependencies:
<!-- Apache Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
I also imported Tomcat's config file context.xml to META-INF/context.xml and edited Context tag like so:
<Context allowCasualMultipartParsing="true">
Nothing seems to be working, any help will be greatly appreciated.
Actually you don't need any filter on the web.xml in order to upload your multipart file with Spring MVC. I've the same configuration in my project and it worked (${spring.version} = 4.3.4.RELEASE):
POM
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Apache Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
HTML
<form method="POST" enctype="multipart/form-data" action="uploadAction">
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
Spring context
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
Spring controller
#PostMapping("/uploadAction")
public String handleFileUpload(#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
File out = new File("outputfile.pdf");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(out);
// Writes bytes from the specified byte array to this file output stream
fos.write(file.getBytes());
System.out.println("Upload and writing output file ok");
} catch (FileNotFoundException e) {
System.out.println("File not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while writing file " + ioe);
} finally {
// close the streams using close method
try {
if (fos != null) {
fos.close();
}
} catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
//storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
}
None of the answers address the issue properly. As per Tomcat documentation, on the configuration of allowCasualMultipartParsing:
Set to true if Tomcat should automatically parse multipart/form-data request bodies when HttpServletRequest.getPart* or HttpServletRequest.getParameter* is called, even when the target servlet isn't marked with the #MultipartConfig annotation (See Servlet Specification 3.0, Section 3.2 for details). Note that any setting other than false causes Tomcat to behave in a way that is not technically spec-compliant. The default is false.
So, what's the compliant way? Reading the official JEE 6 tutorial gives a hint. If you want to use a spec-compliant way with Servlet 3 or newer, your servlet must have a MultipartConfig. You have three choices, depending on how you configure your servlet:
With programmatic configuration: context.addServlet(name, servlet).setMultipartConfig(new MultipartConfigElement("your_path").
With annotations, annotate the servlet's class with #javax.servlet.annotation.MultipartConfig.
With XML configuration, add this to the WEB-INF/web.xml descriptor, in the section of your servlet:
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
For those who get the same exception for PUT method handlers: use POST instead. PUT is incompatible with the multi-part.
More details can be found in the respective answer
It is straight forward from the exception that no multi-part configuration is found. Though you have provided multipartResolver bean.
The problem is that while specifying the MultipartFilter before the Spring Security filter, It tries to get the multipartResolver bean but can't find it. Because it expect the bean name/id as filterMultipartResolver instead of multipartResolver.
Do yourself a favor. Please change the bean configuration like following -
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10000000"/>
</bean>
Add In your config file as:
#Bean(name = "multipartResolver")
public CommonsMultipartResolver CanBeAnyName() {
//configuration
}
I have something similar, but what i did is just send a file without mapping it with any attribute in my model, in your case i would modify this:
<div class="form-group">
<div class="col-lg-3">
<label for="photo">Artist photo:</label>
<input type="file" id="photo" name="file"/>
</div>
</div>
In your controller
#RequestMapping(value = "/newArtist", method = RequestMethod.POST)
public String addArtist(#ModelAttribute("artist") #Valid Artist artist, BindingResult result,
#RequestParam("file") MultipartFile file) throws IOException
//Here read the file and store the bytes into your photo attribute
...
Had the same issue in a Spring Boot application, this exceptions occur several times:
org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is
java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field multipartFile exceeds its maximum permitted size of 1048576 bytes
org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field multipartFile exceeds its maximum permitted size of 1048576 bytes.
Get rid of the tomcat exception with this, with copy catting from http://www.mkyong.com/spring-boot/spring-boot-file-upload-example/
Tomcat large file upload connection reset. Need to let {#link #containerCustomizer()} work properly, other wise exception will occur several times, RequestMapping for uploadError will fail.
#Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
If anyone is using J2EE and not spring framework and still facing issue
what you can try is adding #MultipartConfig annotation on servlet and add enctype="multipart/form-data" inside form tag
If you are using Tomcat 8.
Configure the following in Tomcat's conf/context.xml
Add allowCasualMultipartParsing="true" attribute to context node
Add <Resources cachingAllowed="true" cacheMaxSize="100000" /> inside context node

Resources