Spring Boot file upload/download example

Hello everyone, today we will learn how to upload files/download files in the Spring Boot web application, using Ajax and jQuery. You can download the source code from our GitHub repository.

Following technologies stack being used:

  • Spring Boot 2.1.1.RELEASE
  • Spring 5.1.3.RELEASE 
  • Maven 3
  • JDK 1.8
  • Eclipse Oxygen
  • jQuery
  • Bootstrap
  • Free Marker
  • javascript
  • ajax

User Interface

 
 

Project Structure


 

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<!-- lookup parent from repository -->
</parent>
<groupId>com.knowledgefactory</groupId>
<artifactId>springboot-fileupload-filedownload</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-fileupload-filedownload</name>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- spring mvc, rest -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

<description>springboot-fileupload-filedownload</description>
</project>
  
 

Service Layer(UploadDownloadService.java)

package com.knowledgefactory.knowledgefactorydemo.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class UploadDownloadService {
private static final String path = "D:/files";

public List<String> uploadFile(MultipartFile file) throws Exception {

// Save file on system
if (!file.getOriginalFilename().isEmpty()) {
BufferedOutputStream outputStream = new BufferedOutputStream(
new FileOutputStream
(new File(path, file.getOriginalFilename())));
outputStream.write(file.getBytes());
outputStream.flush();
outputStream.close();
} else {
throw new Exception();
}

List<String> list = new ArrayList<String>();
File files = new File(path);
String[] fileList = ((File) files).list();
for (String name : fileList) {
list.add(name);
}

return list;

}

public List<String> getListofFiles() throws Exception {

List<String> list = new ArrayList<String>();
File files = new File(path);
String[] fileList = ((File) files).list();
for (String name : fileList) {
list.add(name);
}

return list;

}
}
  

Home Controller

package com.knowledgefactory.knowledgefactorydemo;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.knowledgefactory.knowledgefactorydemo.service.UploadDownloadService;

@RestController
public class HomeController {

private static final String path = "D:/files/";
@Autowired
UploadDownloadService service;

@PostMapping("/uploadFile")
public ResponseEntity<List<String>> fileUpload(@RequestParam("file")
MultipartFile file) throws Exception {
return new ResponseEntity<>(service.uploadFile(file), HttpStatus.OK);

}

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(@RequestParam String param)
throws IOException {

File file = new File(path + param);

Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes
(path));
HttpHeaders header = new HttpHeaders();
header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" +
param);
header.add("Cache-Control", "no-cache, no-store, must-revalidate");
header.add("Pragma", "no-cache");
header.add("Expires", "0");
return ResponseEntity.ok().headers(header).contentLength(file.length())
.contentType(MediaType.
parseMediaType("application/octet-stream")).body(resource);
}

@GetMapping("/getListOfFiles")
public ResponseEntity<List<String>> getListOfFiles() throws Exception {
return new ResponseEntity<>(service.getListofFiles(), HttpStatus.OK);

}

}
  

Web Controller

package com.knowledgefactory.knowledgefactorydemo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class WebController {

@GetMapping({ "/", "/view" })
public String listAllUsers() {

return "index";
}
}
  

Spring Boot Main Driver

package com.knowledgefactory.knowledgefactorydemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({ "com" })

public class KnowledgefactorydemoApplication {
// private static final Logger log =
// LoggerFactory.getLogger(KnowledgefactorydemoApplication.class);

public static void main(String[] args) {
SpringApplication.run(KnowledgefactorydemoApplication.class, args);
}
}
  

application.properties

spring.servlet.multipart.enabled=true
# Threshold after which files are written to disk.
spring.servlet.multipart.file-size-threshold=2KB
# Max file size.
spring.servlet.multipart.max-file-size=200MB
# Max Request Size
spring.servlet.multipart.max-request-size=215MB
  

index.ftl

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Knf|File upload and download</title>
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Font Awesome -->
<!-- Ionicons -->
<link rel="stylesheet" 
 href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">

<!-- Theme style -->
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
<!-- Google Font: Source Sans Pro -->
<link href="https://fonts.googleapis.com/css
?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
</head>

<body class="hold-transition layout-top-nav">
<!-- Site wrapper -->
<div class="wrapper">
<!-- Navbar -->
<nav class="main-header navbar
navbar-expand navbar-white navbar-light">
<!-- Left navbar links -->
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link"  
data-widget="pushmenu" href="#"><i class="fas fa-bars">
</i></a>
</li>
<li class="nav-item d-none d-sm-inline-block">
<a href="https://www.knowledgefactory.net/p/donate.html" 
 class="nav-link">Home</a>
</li>
</ul>
</nav>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<!-- Main content -->
<section class="content">
<div class="container">
<h2>Spring Boot-File upload and download</h2>
<hr>
<!-- File Upload From -->
<form action="fileUpload" method="post"  
enctype="multipart/form-data">
<div class="form-group">
<label>Select File</label>  
<input class="form-control" type="file" name="file">
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit" 
 id="uploadfile">Upload</button>
</div>
</form>
<br />
<!-- Bootstrap Progress bar -->
<div class="progress">
<div id="progressBar"  
class="progress-bar progress-bar-success" role="progressbar"
aria-valuenow="0" aria-valuemin="0" 
 aria-valuemax="100" style="width: 0%">0%</div>
</div>
<!-- Alert -->
<div id="alertMsg" style="color: red; font-size: 18px;">
</div>
</div>
<div id="list"></div>
</br>
<div id="result">
<div class="row align-items-center justify-content-center" 
 id="download">
</div>
</div>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="float-right d-none d-sm-block">
<b>Version</b> 1.0.0
</div>
<strong>Copyright &copy; 2014-2019
<a href="http://www.knowledgefactory.net">Knowledge Factory</a>.
</strong> All rights reserved.
</footer>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<!-- /.control-sidebar -->
</div>
<!-- ./wrapper -->
<!-- jQuery -->
<script src="../../plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- overlayScrollbars -->
<script src="../../dist/js/adminlte.min.js"></script>
<script src="../../dist/js/controller.js"></script>
</body>

</html>
  

controller.js

$(function () {
load()
$('button[type=submit]')
.click(
function (e) {
e.preventDefault();
// Disable submit button
$(this).prop('disabled', true);
var form = document.forms[0];
var formData = new FormData(form);
// Ajax call for file uploaling
var ajaxReq = $
.ajax({
url: 'uploadFile',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
xhr: function () {
// Get XmlHttpRequest object
var xhr = $.ajaxSettings.xhr();
// Set onprogress event handler
xhr.upload.onprogress = function (event) {
var perc = Math
.round((event.loaded / event.total) * 100);
$('#progressBar').text(perc + '%');
$('#progressBar').css('width',
perc + '%');
};
return xhr;
},
beforeSend: function (xhr) {
// Reset alert message and progress bar
$('#alertMsg').text('');
$('#progressBar').text('');
$('#progressBar').css('width', '0%');
}
});
// Called on success of file upload
ajaxReq
.done(function (msg) {
$('#alertMsg').text(
"File Uploaded successfully");
$('input[type=file]').val('');
$('button[type=submit]').prop('disabled',
false);
var trHTML = '';
trHTML += '<h3>Download file</h3><ul
class="list-group">'
for (var i = 0; i < msg.length; i++) {
var item = msg[i];
trHTML += '<li class="list-group-item">
<a href="download?param='
+ item
+ '">'
+ item
+ '</a></li>'
}
trHTML += '</ul>'
$('#download').html(trHTML);
});
// Called on failure of file upload
ajaxReq.fail(function (jqXHR) {
$('#alertMsg').text(
jqXHR.responseText + '(' + jqXHR.status
+ ' - ' + jqXHR.statusText + ')');
$('button[type=submit]').prop('disabled', false);
});
});
function load() {
$
.ajax({
type: "GET",
url: "getListOfFiles",
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
success: function (msg) {
var trHTML = '';
trHTML += '<h3>Download file</h3><ul class="list-group">'
for (var i = 0; i < msg.length; i++) {
var item = msg[i];
trHTML += '<li class="list-group-item">
<a href="download?param='
+ item + '">' + item + '</a></li>'
}
trHTML += '</ul>'
$('#download').html(trHTML);
}
});
}
});


 
 

More related topics,

Java - Angular - VueJS - ReactJS

NodeJS - Angular - VueJS - ReactJS

Python - Flask  - Angular - VueJS - ReactJS

Popular posts from this blog

Spring boot video streaming example-HTML5

Spring Boot + OpenCSV Export Data to CSV Example

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring boot web project free download:User Registration System

10 Best Job Posting Sites 2021-2022

Spring Boot + JPA/Hibernate One to Many mapping example

5 Hardest Puzzle,100% fail answers

ReactJS - Bootstrap - Buttons

Spring Boot-AngularJS-Bootstrap-JPA-CRUD

Java security AES,SHA256,SHA512,MD5-Spring Boot Project Free Download