SpringBoot – Upload/Download MultipartFile to MySQL – Bootstrap 4 + JQuery Ajax + Spring Hibernate JPA @Lob Example

springboot-upload-download-multipartfile-to-mysql-bootstrap-4-jquery-ajax-spring-hibernate-jpa-lob

In the tutorial, we will show you how to create a SpringBoot project to download/upload MultipartFile to MySQL using Bootstrap 4, JQuery Ajax, Spring Hibernate JPA @Lob

Related posts:
SpringJPA – save/retrieve Files/Images to MySQL database with @Lob annotation

Technologies

  • Java 8
  • Maven 3.6.1
  • Spring Tool Suite: Version 3.9.4.RELEASE
  • Spring Boot: 2.0.2.RELEASE
  • JQuery Ajax
  • Bootstrap 4
  • MySQL

Demo

Goal

We create a SpringBoot project as below:

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-project structure

-> Upload/Download Form:

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-dowload-files

-> PostgreSQL’s records:

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-records

Practice

We create a SpringBoot project with below dependencies:

  • spring-boot-starter-thymeleaf
  • spring-boot-starter-web
  • spring-boot-starter-data-jpa
  • mysql

-> Details:


	org.springframework.boot
	spring-boot-starter-data-jpa


	org.springframework.boot
	spring-boot-starter-thymeleaf


	org.springframework.boot
	spring-boot-starter-web



	mysql
	mysql-connector-java
	runtime

FrontEnd
Upload Multipart-Form



    Upload MultipartFile
    
    
	%MINIFYHTML255762ec8d442fdca04dfc8f4e56351216%%MINIFYHTML255762ec8d442fdca04dfc8f4e56351217%%MINIFYHTML255762ec8d442fdca04dfc8f4e56351218%%MINIFYHTML255762ec8d442fdca04dfc8f4e56351219%%MINIFYHTML255762ec8d442fdca04dfc8f4e56351220%
 

	

Upload MultipartFile to MySQL


%MINIFYHTML255762ec8d442fdca04dfc8f4e56351221%
Ajax Post/Get MultipartFile

– JQuery Ajax to Post MultipartFile is implemented in ‘\src\main\resources\static\js\postrequest.js’ file:

$(document).ready( () => {
    $("#btnSubmit").click((event) => {
        //stop submit the form, we will post it manually.
        event.preventDefault();
        doAjax();
    });
 
});
 
function doAjax() {
 
    // Get form
    var form = $('#fileUploadForm')[0];
    var data = new FormData(form);
 
    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "/api/file/upload",
        data: data,
        processData: false, //prevent jQuery from automatically transforming the data into a query string
        contentType: false,
        cache: false,
        success: (data) => {
            $("#listFiles").text(data);
        },
        error: (e) => {
            $("#listFiles").text(e.responseText);
        }
    });
}

– JQuery Ajax to Retrieve/Download MultipartFile is implemented in ‘\src\main\resources\static\js\getrequest.js’ file:

$( document ).ready( () => {
	
	var url = window.location;
	
	// GET REQUEST
	$("#btnGetFiles").click( (event) => {
		event.preventDefault();
		ajaxGet();
	});
	
	// DO GET
	function ajaxGet(){
		$.ajax({
			type : "GET",
			dataType: "json",	
			url : "/api/file/all",
			success: (data) => {
				//clear old data
				$("#listFiles").html("");
				
				/*
					render list of files
				*/
				$("#listFiles").append('
    '); $.each(data, (index, file) => { $("#listFiles").append('
  • ' + file.name + '
  • '); }); $("#listFiles").append('
'); }, error : (err) => { $("#listFiles").html(err.responseText); } }); } })
BackEnd
Data Model

– Create a View with @JsonView in ‘View.java’ file:

package com.javasampleapproach.multipartfile.model;

public class View {
	public interface FileInfo {}
}

– Create ‘FileModel.java’ file:

package com.javasampleapproach.multipartfile.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonView;

@Entity
@Table(name="file_model")
public class FileModel {
	@Id
	@GeneratedValue
    @Column(name = "id")
	@JsonView(View.FileInfo.class)
    private Long id;
	
    @Column(name = "name")
    @JsonView(View.FileInfo.class)
	private String name;
    
    @Column(name = "mimetype")
	private String mimetype;
	
	@Lob
    @Column(name="pic")
    private byte[] pic;
	
	public FileModel(){}
	
	public FileModel(String name, String mimetype, byte[] pic){
		this.name = name;
		this.mimetype = mimetype;
		this.pic = pic;
	}
	
	public Long getId(){
		return this.id;
	}
	
	public void setId(Long id){
		this.id = id;
	}
	
	public String getName(){
		return this.name;
	}
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getMimetype(){
		return this.mimetype;
	}
	
	public void setMimetype(String mimetype){
		this.mimetype = mimetype;
	}
	
	public byte[] getPic(){
		return this.pic;
	}
	
	public void setPic(byte[] pic){
		this.pic = pic;
	}
}
JPA Repository

Implement JPA repository in ‘FileRepository.java’ file:

package com.javasampleapproach.multipartfile.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

import com.javasampleapproach.multipartfile.model.FileModel;

@Transactional
public interface FileRepository extends JpaRepository{	
	public FileModel findByName(String name);
}

– Configure @EnableTransactionManagement in main class ‘SpringBootUploadMultipartFile2MySqlApplication.java’:

package com.javasampleapproach.multipartfile;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootUploadMultipartFile2MySqlApplication {

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

Create ‘IndexController.java’ file to serve ‘uploadfile.html’ form:

package com.javasampleapproach.multipartfile.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class IndexController {
    @GetMapping("/")
    public String index() {
        return "uploadfile";
    }
}
Upload/Download RestAPIs

– Implement upload-file RestAPI in ‘UploadFileController.java’ file:

package com.javasampleapproach.multipartfile.controller.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.javasampleapproach.multipartfile.model.FileModel;
import com.javasampleapproach.multipartfile.repository.FileRepository;
 
@RestController
public class UploadFileController {
	
	@Autowired
	FileRepository fileRepository;
 
    /*
     * MultipartFile Upload
     */
    @PostMapping("/api/file/upload")
    public String uploadMultipartFile(@RequestParam("uploadfile") MultipartFile file) {
    	try {
    		// save file to PostgreSQL
	    	FileModel filemode = new FileModel(file.getOriginalFilename(), file.getContentType(), file.getBytes());
	    	fileRepository.save(filemode);
	    	return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
		} catch (	Exception e) {
			return "FAIL! Maybe You had uploaded the file before or the file's size > 500KB";
		}    
    }
}

– Implement download/retrieve files RestAPIs in ‘DownloadFileController.java’ file:

package com.javasampleapproach.multipartfile.controller.rest;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.annotation.JsonView;
import com.javasampleapproach.multipartfile.model.FileModel;
import com.javasampleapproach.multipartfile.model.View;
import com.javasampleapproach.multipartfile.repository.FileRepository;
 
@RestController
public class DownloadFileController {
	
	@Autowired
	FileRepository fileRepository;

	/*
	 * List All Files
	 */
    @JsonView(View.FileInfo.class)
	@GetMapping("/api/file/all")
	public List getListFiles() {
		return fileRepository.findAll();
	}
	
    /*
     * Download Files
     */
	@GetMapping("/api/file/{id}")
	public ResponseEntity getFile(@PathVariable Long id) {
		Optional fileOptional = fileRepository.findById(id);
		
		if(fileOptional.isPresent()) {
			FileModel file = fileOptional.get();
			return ResponseEntity.ok()
					.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
					.body(file.getPic());	
		}
		
		return ResponseEntity.status(404).body(null);
	}
}
MySQL Connection

– Add setting in ‘application.properties’ file:

spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username=root
spring.datasource.password=12345
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false
spring.jpa.hibernate.ddl-auto=create-drop	
Run & Check Results

Run the SpringBoot project, then makes upload/download requests ->

Upload Files

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-upload-a-file

-> Browser Networks logs:

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-upload-file-network-logs

-> MySQL records:

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-records

Retrieve Files

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-retrieve-all-files

-> Browser Network logs:

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-retrieves-all-files-network-logs

Download Files

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-dowload-files

-> Browser Network logs:

SpringJPA-Upload-Download-MultipartFile-to-PostgreSQL-download-files-network-logs

SourceCode

SpringBootUploadMultipartFile2MySQL



By grokonez | May 31, 2018.

Last updated on September 15, 2018.



Related Posts


1 thought on “SpringBoot – Upload/Download MultipartFile to MySQL – Bootstrap 4 + JQuery Ajax + Spring Hibernate JPA @Lob Example”

  1. but can you help me I tried to relate like this for but it does not work method MultipartFile Upload:

    @Entity
    @Table(name="file_model")
    public class FileModel  {
    	@Id
    	@GeneratedValue
           @Column(name = "id")
    	@JsonView(View.FileInfo.class)
        private Long id;
           @Column(name = "name")
           @JsonView(View.FileInfo.class)
        private String name;
           @Column(name = "mimetype")
        private String mimetype;
          @Lob
          @Column(name="pic")
        private byte[] pic;
         @ManyToOne(optional = false)
         @JoinColumn(name = "user_id")
       private User user;
    ::::::::::::::::::::::::::::::::::::::::::::::::::
    @Entity
    public class User {
            @Id
            @GeneratedValue
            private Long id;
            private String firstName;
            private String lastName;
            @OneToMany(mappedBy)
            private Collection fileModels = new ArrayList();
    }
    ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    
        @PostMapping("/api/file/upload")
        public String uploadMultipartFile(@RequestParam("uploadfile") MultipartFile file,User user) {
        	try {
        		// save file to PostgreSQL
    	    	FileModel filemode;
    			filemode = new FileModel(file.getOriginalFilename(), file.getContentType(), file.getBytes(), user);
    
    			fileRepository.save(filemode);
    

Got Something To Say:

Your email address will not be published. Required fields are marked *

*