11. Spring - Concepts of file upload multipart.

 


Concepts of file upload multipart.

Multipart is http request that client browser is used to differentiate the binary file (image, files) and the data to send to the server


@transient-this is helpful to store binary file (uploading image)

@Transient
Private MultipartFile file;


Enctype – default enctype of a from is encored.it a long encored string.orthr anctype is text/lain

enctype="multipart/form-data"

 We need to tell spring to handle the multipart request. Spring use 2 interfaces.


Web.xml should be configured to upload file.



Steps

1.      From should be multipart ectype

2.      Tell to spring there should be multipart request. That should be handled (dispatcher-servlet.xml).

3.      After that we want to do configurations for file upload (web.xml).

 

All steps have been described bellow with example codes.

 

Applying custom validator using spring on form.


@RequestMapping("/product")

public ModelAndView manageProduct() {    

 mv.addObject("message", "Product submitted successfully!");                 

returnmv;

}



Full code for form submission and validation.        

Using spring valuator this can be done. We need bellow dependencies for that.

<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>


For maltipart request.

Dependencies(pom.xml)

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>


For maltipart request.

Depatcher-sevlet.xml

<bean id="multipartResolver"
class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>


For maltipart request.

Web.xml

<!-- Configuring front-controller -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- For throwing exception -->
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
<multipart-config>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
</servlet>



With maltipart request.

Form

<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<sf:form class="form-horizontal" modelAttribute="product" action="${contextRoot}/manage/product" method="POST" enctype="multipart/form-data">
<div class="form-group">

<label class="control-label col-md-4">Name</label>
<div class="col-md-8">
<sf:input type="text" path="name" class="form-control" placeholder="Product Name" />
<sf:errors path="name" cssClass="help-block" element="em"/>
</div>
</div>

<div class="form-group">
<label class="control-label col-md-4">Upload a file</label>
<div class="col-md-8">
<sf:input type="file" path="file" class="form-control"/>
<sf:errors path="file" cssClass="help-block" element="em"/>
</div>
</div>

<div class="form-group">
<label class="control-label col-md-4">Category</label>
<div class="col-md-8">
<sf:select path="categoryId" items="${categories}" itemLabel="name" itemValue="id" class="form-control"/>
</div>
</div>
<sf:hidden path="id"/>
<sf:hidden path="code"/>
<div class="form-group">
<div class="col-md-offset-4 col-md-4">
<input type="submit" name="submit" value="Save" class="btn btn-primary"/>
</div>
</div>

</sf:form>


Entity class

import java.io.Serializable;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.annotation.JsonIgnore;

@Component
@Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
// private fields
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Private int id;
private String code;
@NotBlank(message = "Please enter the product name!")
Private String name;
@Column(name = "category_id")
@JsonIgnore
Private int categoryId;

@Transient
Private MultipartFile file;
// default constructor
public Product() {
this.code = "PRD" + UUID.randomUUID().toString().substring(26).toUpperCase();
}
//setter and getters should be added.
}


Controller class

BindingResult results shoud be placed after @ModelAttribute and Model shoud be place after BindingResult.

@ModelAttribute("product") Product mProduct, BindingResult results, Model model

@RequestMapping("/product")
public ModelAndView manageProduct(@RequestParam(name="success",required=false) String success) {
ModelAndView mv = new ModelAndView("page");
mv.addObject("product", nProduct);
if(success != null) {
mv.addObject("message", "Product submitted successfully!");
}
return mv;
}

@RequestMapping(value = "/product", method=RequestMethod.POST)
public String managePostProduct(@Valid@ModelAttribute("product") Product mProduct,
BindingResult results, Model model, HttpServletRequest request) {

// mandatory file upload check
if(mProduct.getId() == 0) {
new ProductValidator().validate(mProduct, results);
}else {
// edit check only when the file has been selected
if(!mProduct.getFile().getOriginalFilename().equals("")) {
new ProductValidator().validate(mProduct, results);
}
}

if(results.hasErrors()) {
model.addAttribute("message", "Validation fails for adding the product!");
model.addAttribute("userClickManageProduct",true);
return"page";
}

if(mProduct.getId() == 0 ) {
productDAO.add(mProduct);
}else {
productDAO.update(mProduct);
}
//upload the file
if(!mProduct.getFile().getOriginalFilename().equals("") ){
FileUtil.uploadFile(request, mProduct.getFile(), mProduct.getCode());
}

return"redirect:/manage/product?success=product";
}

@ModelAttribute("categories")
public List<Category> modelCategories() {
return categoryDAO.list();
}

For maltipart request.

Image validates.

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

publicclassProductValidatorimplementsValidator {

@Override
publicbooleansupports(Class<?>clazz) {
returnProduct.class.equals(clazz);
}

@Override
publicvoidvalidate(Objecttarget, Errorserrors) {
Productproduct = (Product) target;
if(product.getFile() == null || product.getFile().getOriginalFilename().equals("")) {
errors.rejectValue("file", null, "Please select a file to upload!");
return;
}
if(! (product.getFile().getContentType().equals("image/jpeg") ||
product.getFile().getContentType().equals("image/png")) ||
product.getFile().getContentType().equals("image/gif")
)
{
errors.rejectValue("file", null, "Please select an image file to upload!");
return;
}

}

}

 For maltipart request.

Save image

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {

private static final String ABS_PATH = "E:/JAVAApp/online-shopping/onlineshopping/src/main/webapp/assets/images/";
private static String REAL_PATH = null;
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
public static boolean uploadFile(HttpServletRequest request, MultipartFile file, String code)
{
// get the real server path
REAL_PATH = request.getSession().getServletContext().getRealPath("/assets/images/");
logger.info(REAL_PATH);
// create the directories if it does not exist
if(!newFile(REAL_PATH).exists()) {
newFile(REAL_PATH).mkdirs();
}
if(!newFile(ABS_PATH).exists()) {
newFile(ABS_PATH).mkdirs();
}
try {
//transfer the file to both the location
file.transferTo(newFile(REAL_PATH + code + ".jpg"));
file.transferTo(newFile(ABS_PATH + code + ".jpg"));
}
catch(IOException ex) {
ex.printStackTrace();
}
returntrue;
}
public static void uploadNoImage(HttpServletRequest request, Stringcode) {
// get the real server path
REAL_PATH = request.getSession().getServletContext().getRealPath("/assets/images/");
String imageURL = "http://placehold.it/640X480?text=No Image";
String destinationServerFile = REAL_PATH + code + ".jpg";
String destinationProjectFile = REAL_PATH + code + ".jpg";
try {
URLurl = newURL(imageURL);
try (
InputStreamis = url.openStream();
OutputStreamos REAL_PATH = newFileOutputStream(destinationServerFile);
OutputStreamos ABS_PATH = newFileOutputStream(destinationProjectFile);
){
byte[] b = newbyte[2048];
intlength;
while((length = is.read(b))!= -1) {
osREAL_PATH.write(b, 0, length);
osABS_PATH.write(b, 0, length);
}
}
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}


Comments

Popular posts from this blog

09.Data Binding.

Database - Topics

02. Spring – Creating spring project clone it with GIT step by step.