使用百里香叶的春季启动上传和下载示例。在本文中,我们将学习如何从数据库上传和下载文件。此外,我们将看到如何显示数据库中的图像。
上传和下载图像是任何应用程序的重要组成部分之一。众所周知,我们使用 Spring Boot 使开发过程变得简单。因此,在这里我们将创建一个示例来从数据库上传和下载文件。我们将在视图层使用百里香叶模板。Spring Data JPA 将在数据访问层使用。这里的关系数据库是MYSQL。
在此示例中,我们将创建一个视图,在其中查看如何上传和下载文件。
第 1 步:打开 IDE STS-弹簧工具套件
第 2 步:转到 Spring 入门项目>文件。
步骤3: 现在,填写如下所示的所有字段,然后单击下一步。
步骤4: 现在,添加百里香叶,春季数据JPA,龙目岛和春季网络的依赖项,然后单击下一步>完成。
现在,等待一段时间,您的项目结构将准备就绪。转到pom.xml文件,您将看到将自动添加以下依赖项
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
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
mysql> create database db_demo;
# change the port
server.port=8888
#Database Configrations
spring.datasource.url=jdbc:mysql://localhost:3306/db_demo
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
#Multipart
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=200MB
spring.servlet.multipart.max-request-size=215MB
Student.java
package com.example.thymeleaf.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Entity
@Table(name = "student")
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String profilePicture;
private long size;
private byte [] content;
}
在数据库中,它将像这样显示
现在,使用 MYSQL 工作台将 TinyBLOB 数据类型更改为中等 Blob。
这里的存储库是 DAO 层,它执行所有数据库操作。创建 StudentRepository 接口,该接口将扩展 JPARepository
package com.example.thymeleaf.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.thymeleaf.model.Student;
public interface StudentRepository extends JpaRepository {
}
在这里,创建三种方法来保存学生信息、检索学生信息和按 id 获取学生信息。
StudentService.java
package com.example.thymeleaf.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.thymeleaf.model.Student;
import com.example.thymeleaf.repository.StudentRepository;
@Service
public class StudentService {
@Autowired
private StudentRepository repository;
public Student createStudent(Student student) {
return repository.save(student);
}
public List getAllStudent(){
return repository.findAll();
}
public Optional findStudentById(long id){
return repository.findById(id);
}
}
对网页的请求将由控制器类中的处理程序方法使用 @GetMapping 处理。
package com.example.thymeleaf.controller;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.example.thymeleaf.model.Student;
import com.example.thymeleaf.service.StudentService;
import com.sun.xml.txw2.Document;
@Controller
public class StudentController {
@Autowired
private StudentService service;
@GetMapping("/")
public String home(Model model) {
List list = service.getAllStudent();
model.addAttribute("list", list);
return "index";
}
@PostMapping("/upload")
public String fileUpload(@RequestParam("file") MultipartFile file, Model model) throws IOException {
Student student = new Student();
String fileName = file.getOriginalFilename();
student.setProfilePicture(fileName);
student.setContent(file.getBytes());
student.setSize(file.getSize());
service.createStudent(student);
model.addAttribute("success", "File Uploaded Successfully!!!");
return "index";
}
@GetMapping("/downloadfile")
public void downloadFile(@Param("id") Long id , Model model, HttpServletResponse response) throws IOException {
Optional temp = service.findStudentById(id);
if(temp!=null) {
Student student = temp.get();
response.setContentType("application/octet-stream");
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename = "+student.getProfilePicture();
response.setHeader(headerKey, headerValue);
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(student.getContent());
outputStream.close();
}
}
@GetMapping("/image")
public void showImage(@Param("id") Long id, HttpServletResponse response, Optional student)
throws ServletException, IOException {
student = service.findStudentById(id);
response.setContentType("image/jpeg, image/jpg, image/png, image/gif, image/pdf");
response.getOutputStream().write(student.get().getContent());
response.getOutputStream().close();
}
}
@Controller注释将学生控制器类标记为请求处理程序。现在让我们打破上面的代码并理解它。
将文件上传到数据库
@PostMapping("/upload")
public String fileUpload(@RequestParam("file") MultipartFile file, Model model) throws IOException {
Student student = new Student();
String fileName = file.getOriginalFilename();
student.setProfilePicture(fileName);
student.setContent(file.getBytes());
student.setSize(file.getSize());
service.createStudent(student);
model.addAttribute("success", "File Uploaded Successfully!!!");
return "index";
}
从数据库下载文件
@GetMapping("/downloadfile")
public void downloadFile(@Param("id") Long id , Model model, HttpServletResponse response) throws IOException {
Optional temp = service.findStudentById(id);
if(temp!=null) {
Student student = temp.get();
response.setContentType("application/octet-stream");
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename = "+student.getProfilePicture();
response.setHeader(headerKey, headerValue);
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(student.getContent());
outputStream.close();
}
}
显示数据库中的文件
@GetMapping("/image")
public void showImage(@Param("id") Long id, HttpServletResponse response, Optional student)
throws ServletException, IOException {
student = service.findStudentById(id);
response.setContentType("image/jpeg, image/jpg, image/png, image/gif, image/pdf");
response.getOutputStream().write(student.get().getContent());
response.getOutputStream().close();
}
转到 src/main/resources/template 文件夹并创建一个 index.html 文件。现在在寄存器中.html文件确保添加以下代码:
要了解如何迭代百里香叶中的对象列表,请查看这篇文章 使用 Spring 引导在百里香叶中迭代列表
File Upload & Download
现在,运行 UploadAndDownloadApplication 并转到 localhost:8888 并查看以下输出。
通过这种方式,我们学会了如何从/向数据库上传、下载和显示图像。