Spring Boot File Download Using Ajax Example | Code Factory

package com.codeFactory;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
public class SpringBootFileDownloadUsingAjax {
public static void main(String[] args) {
SpringApplication.run(SpringBootFileDownloadUsingAjax.class, args);
package com.codeFactory.controller;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLConnection;
import java.nio.file.Files;
import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
public class FileDownloadController {
public String index() {
return "download";

@RequestMapping(value = "/downloadFile", method = RequestMethod.POST)
public void downloadFile(HttpServletResponse response) throws Exception {
try {
String fileName = "Aston_Martin_DBS.jpg";
String filePath = "R:\\Temp\\" + fileName;

try {
File file = new File(filePath);
FileInputStream in = new FileInputStream(filePath);

response.setHeader("Content-Disposition","attachment; filename=\"" + fileName +"\"");

FileCopyUtils.copy(in, response.getOutputStream());
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (Exception e) {
<title>Spring Boot File Download Using Ajax Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<h1>Spring Boot File Download Using Ajax Example</h1>
<input type="button" value="Download File" onclick="downloadFile()"/>
function downloadFile() {
var xhr = new XMLHttpRequest();
xhr.open('POST', "../downloadFile", true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
if (this.status === 200) {
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, '');
var type = xhr.getResponseHeader('Content-Type');
var blob = typeof File === 'function'
? new File([this.response], filename, { type: type })
: new Blob([this.response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created.
// These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
} else {
window.location = downloadUrl;
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<relativePath /> <!-- lookup parent from repository -->
<description>Spring Boot File Download Using Ajax Example</description>




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

UiPath RPA on Oracle R12 EBS

The Case for SaaS ERP

3 Ways of Rendering on The Web

Why You should really use Wilcom TrueSizer

Do you want to use Django for REST API? Consider it.

Big Data: Three Different Ways to Handle Data That Can’t Fit into Memory (Part I)

Pass secrets to Docker build to fetch private Github repositories

My First CLI Project

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Code Factory

Code Factory

More from Medium

Spring vs Spring Boot

How Lombok @SneakyThrows is hacking Java !

How to Create User in Azure AD B2C by using Microsoft Graph and Java