Skip to main content

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

This article shows you how to upload file/download files in the Spring Boot web application, using Ajax and jquery.
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

Home Controller
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
@Controller
public class WebController {
 @GetMapping({  "/","/view" })
 public String listAllUsers() {
   return "index";
 }
}
Spring Boot
@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);
 }
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);
     }
    });
 }
});
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

Comments

Post a Comment

Popular posts from this blog

Spring boot video streaming example-HTML5

This article shows you how to stream MP4 video in Spring Boot web application 
User Interface

Project Structure

Home Controller
@Controller
public class HomeController {
 @Autowired
 private MyResourceHttpRequestHandler handler;
 private final static File MP4_FILE = new File("D:\\videofiles\\video1.mp4");
 // supports byte-range requests
 @GetMapping("/index")
 public String home() {
  return "index";
 }
 // supports byte-range requests
 @GetMapping("/byterange")
 public void byterange( HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setAttribute(MyResourceHttpRequestHandler.ATTR_FILE, MP4_FILE);
  handler.handleRequest(request, response);
 }}
Spring Boot 
@SpringBootApplication
@ComponentScan({ "com" })
public class KnowledgefactorydemoApplication {
 public static void main(String[] args) {
  SpringApplication.run(KnowledgefactorydemoApplication.class, args);
 }}
MyResource HttpRequestHandler
@Componen…

DataTable-Pagination example with Spring boot,jQuery and ajax free download

This article shows you DataTable-Pagination example with Spring boot, jQuery and ajax. 

Following technologies stack being used:
Spring Boot 2.1.1.RELEASESpring 5.1.3.RELEASE Maven 3DatatablejQueryFree Markerjavascriptajax Project Structure
View(index.ftl) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Knf|Pagination-Datatables</title> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../../css/jquery.dataTables.min.css"> <body>  <section class="content">   <div class="container-fluid">    <table id="example" class="display" style="width: 100%">     <thead>      <tr>       <th>First name</th>       <th>La…

9 Best Job Posting Sites for Employee 2020-2022

One of the most common ways today’s job seekers uncover employment opportunities are by using online sources. There are hundreds of job boards, both generic and niche, as well as aggregators, social media channels, networking groups, and staffing company websites to choose from. The good news is they provide plenty of listings. The bad news is you can be easily overwhelmed by so many options. Here, knowledge factory offers 9 of what is generally considered the best job search websites around. There are many others, of course, but this list of best job search websites should give you a good starting point for your next job hunt: 1. LinkedIn
This top networking site allows you to find jobs through your extended network. User profiles serve as resumes. You can easily share career-related content and solicit or supply recommendations. Additionally, you can join groups, participate in conversations, and follow companies you find interesting and relevant to your job search. Premium pai…