"Welcome To Ashok IT"
"Spring Boot and MicroServices"
Topic : SpringBootMVC Development
Date : 23/05/2025
(Session - 51)
_____________________________________________________________________________________________________________________
File Uploading & Downloading
============================
* File Uploading is nothing but sending copy of file from client machine to server machine is called "Uploading".
* File Downloading is Process of getting file from server machine into client machine is called "Downloading".
* Most of the applications in realworld this is common task for File Uploading and Downloading.
* In the Standalone application we can store the files into Database Software directly in the form of Lobs(CLOB,BLOB)
* In the Web application (or) Distributed application we can store uploaded files into servermachine at particular location (or) we can store the uploaded files into Cloud(AWS(S3)).
Java <----------> AWS Service <------------> aws-sdk
Python <----------> AWS Service <------------> boto,boto3 libraries
* In the current Application we are just storing the files into particular location of Server machine and we can enhance the functionality to store location of file in database column instead of storing file content into database.
* During the File Uploading Process if our request contains simple input fields + uploaded file means that request to be considered as "Multi-part" request.
* To Store the Uploaded file into Model class we need to take one multipart property.
Steps
=====
* When we are doing the file uploading process in webapplication development either by Servlets & JSP (or) Spring MVC (or) Spring Boot MVC we need to follow the below steps
1) In the view page either html page (or) JSP Page we need to have tag which can be used to browse the file from Hard drive.
2) Make sure Html Form method should be used as "POST".
3) Enabling the Multipart Request at form tag level using following attribute enctype="multipart/form-data".
Multipart Request means "plain text + Uploaded File Content"
* Normally to hold the form data at server side we need to take one model class, Inorder to hold the uploaded file content as programmer we need to take one Multipart Property.
FileController.java
===================
package com.ashokit.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.ashokit.dto.UserDto;
import jakarta.servlet.http.HttpServletResponse;
@Controller
public class FileController {
public FileController() {
System.out.println("Request Controller class default constructor!!!");
}
//getting home page
@RequestMapping(value ="/",method=RequestMethod.GET)
public String getHomePage(Model model) {
model.addAttribute("user", new UserDto()); //creating the object for command class
//creating the content for Dropdown while rendering the registrationForm.jsp
List qualificationList = new ArrayList();
qualificationList.add("MCA");
qualificationList.add("CSE");
model.addAttribute("qualificationsList", qualificationList);
return "registrationForm";
}
@RequestMapping(value="saveProfile",method=RequestMethod.POST)
public ModelAndView saveProfileData(@ModelAttribute("user") UserDto user) {
ModelAndView mav = new ModelAndView();
MultipartFile uploadFile = user.getProfilePic();
String uploadStatus ="Uploaded Success";
String viewPageName="registrationForm";
File totalFilesList[] = null;
// E:\springBootUploadFiles\
File directoryLocation = new File("E:"+File.separator+"springBootUploadFiles"+File.separator);
//checking the file location directory is existed or not
if(!directoryLocation.exists()) {
directoryLocation.mkdir();
}
if(!uploadFile.isEmpty()) {
String uploadFileName = uploadFile.getOriginalFilename();//uploaded file name
System.out.println("Absoulte Path::::" + directoryLocation.getAbsolutePath());
System.out.println("Upload File Name::::::" + uploadFileName);
String uploadedFilePath = directoryLocation.getAbsolutePath()+File.separator+uploadFileName;
try(FileOutputStream fos = new FileOutputStream(uploadedFilePath)){
byte[] bt = uploadFile.getBytes();
fos.write(bt);//writing the uploaded file data into destination location
totalFilesList = directoryLocation.listFiles();//getting the list of files available in directory
viewPageName = "fileUploadStatus";
} catch (Exception e) {
e.printStackTrace();
}
}else {
uploadStatus ="Please Browse File To Complete the Form Submission!!!";
}
mav.addObject("totalFilesList", totalFilesList);
mav.addObject("uploadStatus",uploadStatus);
mav.setViewName(viewPageName);
return mav;
}
@RequestMapping(value="downloadFile", method=RequestMethod.GET)
public void fileDownload(@RequestParam("filename") String fileName,HttpServletResponse response){
File directoryLocation = new File("E:"+File.separator+"springBootUploadFiles");
try(FileInputStream fis = new FileInputStream(directoryLocation.getAbsolutePath()+File.separator+fileName)) {
response.setHeader("Content-Disposition","attachment;filename="+fileName);//getting the popup message to download the file
IOUtils.copy(fis, response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
throw new RuntimeException("IO Error Writing file to Output Stream");
}
}
}
UserDto.java
============
package com.ashokit.dto;
import org.springframework.web.multipart.MultipartFile;
public class UserDto {
private String firstName;
private String lastName;
private String qualification;
private MultipartFile profilePic;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public String getQualification() {
return qualification;
}
public void setProfilePic(MultipartFile profilePic) {
this.profilePic = profilePic;
}
public MultipartFile getProfilePic() {
return profilePic;
}
}
application.properties
======================
# Datasource Configuration
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=root
# MVC Configuration
server.port=1234
spring.mvc.view.prefix=/views/
spring.mvc.view.suffix=.jsp
server.servlet.context-path=/32_SpringBootMVC_File_Uploading_Downloading_App
#Hibernate Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
#MultiPart Configuration
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB
registrationForm.jsp
====================
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="spring" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
registrationForm.jsp
Welcome To AshokIT Spring Boot MVC File Uploading & Downloading Application!!!!