Spring Boot upload/download file example using Ajax and jQuery-download source code

Hello everyone, today we will learn how to upload file/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



Service Layer(UploadDownloadService.class)

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);
}
});
}
});

Comments

Post a Comment