https://howtodoinjava.com/spring-mvc/spring-mvc-download-file-controller-example/
Other Referenced Sites:
https://howtodoinjava.com/spring-mvc/spring-mvc-multi-file-upload-example/
@Controller
@RequestMapping("/download")public class FileDownloadController { @RequestMapping("/pdf/{fileName:.+}") public void downloadPDFResource( HttpServletRequest request, HttpServletResponse response, @PathVariable("fileName") String fileName) { //If user is not authorized - he should be thrown out from here itself //Authorized user will download the file String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/downloads/pdf/"); Path file = Paths.get(dataDirectory, fileName); if (Files.exists(file)) { response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename="+fileName); try { Files.copy(file, response.getOutputStream()); response.getOutputStream().flush(); } catch (IOException ex) { ex.printStackTrace(); } } }}
http://localhost:8080/springmvcexample/download/pdf/sample.pdf=======================================================================
@Controller@RequestMapping("/download")public class FileDownloadController { @RequestMapping("/pdf/{fileName:.+}") public void downloadPDFResource( HttpServletRequest request, HttpServletResponse response, @PathVariable("fileName") String fileName, @RequestHeader String referer) { //Check the renderer if(referer != null && !referer.isEmpty()) { //do nothing //or send error } //If user is not authorized - he should be thrown out from here itself //Authorized user will download the file String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/downloads/pdf/"); Path file = Paths.get(dataDirectory, fileName); if (Files.exists(file)) { response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename="+fileName); try { Files.copy(file, response.getOutputStream()); response.getOutputStream().flush(); } catch (IOException ex) { ex.printStackTrace(); } } }}
Spring MVC Multiple File Upload Example
*************************************************************************
pom.xml
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version></dependency><dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version></dependency>
1. Spring MVC MultipartFile Interface
File file = new File(...);multipartFile.transferTo(file);
2. Domain class for file upload
Product.java
public class Product implements Serializable { private static final long serialVersionUID = 74458L; @NotNull @Size(min=1, max=10) private String name; private String description; private List<MultipartFile> images; //getters and setters}
3. Spring MVC multi-file upload controller
DemoProductController.java
@Controllerpublic class DemoProductController { @RequestMapping("/save-product") public String uploadResources( HttpServletRequest servletRequest, @ModelAttribute Product product, Model model) { //Get the uploaded files and store them List<MultipartFile> files = product.getImages(); List<String> fileNames = new ArrayList<String>(); if (null != files && files.size() > 0) { for (MultipartFile multipartFile : files) { String fileName = multipartFile.getOriginalFilename(); fileNames.add(fileName); File imageFile = new File(servletRequest.getServletContext().getRealPath("/image"), fileName); try { multipartFile.transferTo(imageFile); } catch (IOException e) { e.printStackTrace(); } } } // Here, you can save the product details in database model.addAttribute("product", product); return "viewProductDetail"; } @RequestMapping(value = "/product-input-form") public String inputProduct(Model model) { model.addAttribute("product", new Product()); return "productForm"; }}
4. Spring MVC configuration changes
beans.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20848820" /></bean>
Equivalent Java annotation configuration is :
@Bean(name = "multipartResolver")public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(20848820); return multipartResolver;}
<mvc:resources mapping="/image/**" location="/image/" />
Equivalent Annotation Configuration@Bean(name = "multipartResolver")public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(20848820); return multipartResolver;}
Completer beans.xml file used.
xsi:schemaLocation="http://www.springframework.org/schema/beans <context:component-scan base-package="com.howtodoinjava.demo" /> <mvc:resources mapping="/image/**" location="/image/" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages" /> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="20848820" /> </bean> </beans>
productForm.jsp
<!DOCTYPE html><html><head><title>Add Product Form</title></head><body> <div id="global"> <form:form commandName="product" action="save-product" method="post" enctype="multipart/form-data"> <fieldset> <legend>Add a product</legend> <p> <label for="name">Product Name: </label> <form:input id="name" path="name" cssErrorClass="error" /> <form:errors path="name" cssClass="error" /> </p> <p> <label for="description">Description: </label> <form:input id="description" path="description" /> </p> <p> <label for="image">Product Images: </label> <input type="file" name="images" multiple="multiple"/> </p> <p id="buttons"> <input id="reset" type="reset" tabindex="4"> <input id="submit" type="submit" tabindex="5" value="Add Product"> </p> </fieldset> </form:form> </div></body></html>
viewProductDetail.jsp============================================================================
<!DOCTYPE html><html><head><title>Save Product</title></head><body><div id="global"> <h4>The product has been saved.</h4> <h5>Details:</h5> Product Name: ${product.name}<br/> Description: ${product.description}<br/> <p>Following files are uploaded successfully.</p> <ol> <c:forEach items="${product.images}" var="image"> <li>${image.originalFilename} <img width="100" src="<c:url value="/image/"/>${image.originalFilename}"/> </li> </c:forEach> </ol></div></body></html>
No comments:
Post a Comment