小言_互联网的博客

使用 MySQL、Thymeleaf 和 Spring Boot Framework 上传、存储和查看图像

230人阅读  评论(0)

在本文中,我们将使用 Spring Boot 框架从头开始构建映像库应用程序,用户可以在其中列出其映像。

以下是我们将在应用程序中实现的功能。

  • 用户可以列出他们的图像以及详细信息,例如,
    1. 名字
    2. 描述
    3. 图像
    4. 价格。(如果他们想卖)。
  • 任何人都可以查看列出的图像以及所有详细信息。

注意:我们将使用 MySQL 数据库来存储所有图像详细信息。

最终应用

 

 

注意:视频教程可在底部找到。

您可以在本文的底部找到源代码。

请严格按照以下提及的步骤从头开始构建应用程序。

第 1 步:从 Spring Initializr 创建一个项目。

  • 转到 Spring 初始化器。
  • 输入组名称 com.pixeltrice
  • 提及工件 ID,spring-boot-image-gallery-app
  • 添加以下依赖项。
    1. 春网
    2. 春季数据 JPA
    3. MySQL 驱动程序
    4. 百里香叶

第 2 步:按“生成”按钮,该项目将下载到您的本地系统上。

第 3 步:现在解压缩项目并将其解压缩到本地系统。

第 4 步:之后,将项目导入 IDE 中,例如 Eclipse。

选择文件 -> 导入 -> 现有 Maven 项目 -> 浏览 -> 选择文件夹 spring-boot-image-gallery-app-> 完成。

第 5 步:在应用程序中配置属性。属性

应用程序属性


  
  1. # Set here configurations for the database connection
  2. spring.datasource.url=jdbc:mysql://localhost:3306/imageGalleryApp?autoReconnect=true&useSSL=false
  3. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  4. spring.datasource.username=root
  5. spring.datasource.password=your MySQL Password
  6. # Specify the DBMS
  7. spring.jpa.database = MYSQL
  8. # Show or not log for each sql query
  9. spring.jpa.show-sql = true
  10. #create-drop| update | validate | none
  11. spring.jpa.hibernate.ddl-auto = update
  12. # SQL dialect for generating optimized queries
  13. spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
  14. uploadDir=/resources
  15. #Enable multipart uploads
  16. spring.servlet.multipart.enabled=true
  17. # Threshold after which files are written to disk.
  18. spring.servlet.multipart.file-size-threshold=2KB
  19. # Max file size.
  20. spring.servlet.multipart.max-file-size=200MB
  21. # Max Request Size
  22. spring.servlet.multipart.max-request-size=215MB

所有属性都是不言自明的,您通过查看它很容易理解。

第 6 步:为图像创建实体类。

在此步骤中,我们将定义实体类,该实体类将与数据库中存在的表进行映射。

ImageGallery.java


  
  1. package com.pixeltrice.springbootimagegalleryapp.entity;
  2. import java.util.Arrays;
  3. import java.util.Date;
  4. import javax.persistence.Column;
  5. import javax.persistence.Entity;
  6. import javax.persistence.GeneratedValue;
  7. import javax.persistence.GenerationType;
  8. import javax.persistence.Id;
  9. import javax.persistence.Lob;
  10. import javax.persistence.Table;
  11. import javax.persistence.Temporal;
  12. import javax.persistence.TemporalType;
  13. @Entity
  14. @Table(name = "image_gallery")
  15. public class ImageGallery {
  16. @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
  17. @Column(name = "id", nullable = false, unique = true)
  18. private Long id;
  19. @Column(name = "name", nullable = false)
  20. private String name;
  21. @Column(name = "description", nullable = false)
  22. private String description;
  23. @Column(name = "price",nullable = false, precision = 10, scale = 2)
  24. private double price;
  25. @Lob
  26. @Column(name = "Image", length = Integer.MAX_VALUE, nullable = true)
  27. private byte[] image;
  28. @Temporal(TemporalType.TIMESTAMP)
  29. @Column(name = "create_date", nullable = false)
  30. private Date createDate;
  31. public ImageGallery() {}
  32. public Long getId() {
  33. return id;
  34. }
  35. public void setId(Long id) {
  36. this.id = id;
  37. }
  38. public String getName() {
  39. return name;
  40. }
  41. public void setName(String name) {
  42. this.name = name;
  43. }
  44. public String getDescription() {
  45. return description;
  46. }
  47. public void setDescription(String description) {
  48. this.description = description;
  49. }
  50. public double getPrice() {
  51. return price;
  52. }
  53. public void setPrice(double price) {
  54. this.price = price;
  55. }
  56. public byte[] getImage() {
  57. return image;
  58. }
  59. public void setImage(byte[] image) {
  60. this.image = image;
  61. }
  62. public Date getCreateDate() {
  63. return createDate;
  64. }
  65. public void setCreateDate(Date createDate) {
  66. this.createDate = createDate;
  67. }
  68. @Override
  69. public String toString() {
  70. return "Product [id=" + id + ", name=" + name + ", description=" + description + ", price=" + price + ", image="
  71. + Arrays.toString(image) + ", createDate=" + createDate + "]";
  72. }
  73. }

在实体上方,该类将与 MySQL 数据库中名为“image_gallery”的表进行映射。由于该类带有@Entity注释标记,因此它是一个持久 Java 类。

@Table注解指示与上述实体类映射的数据库表名。 @Id注解用于将变量表示为表中的主键。

@Column注释用于表示与上述变量或字段映射的列的名称。

@Lob注释用于将大型对象存储到数据库中,例如字节数组或大型字符串。在我们的例子中,我们以字节数组的形式存储图像。

此注释用于指定使用 Lob 标记或批注的字段应在数据库表中以 BLOB(二进制大对象)数据类型的形式表示。

第 7 步:为 ImageGallery 实体类创建存储库接口

在这里,我们将创建存储库,该存储库将与我们的数据库通信并执行所有类型的 CRUD 操作。在此步骤中,我们将扩展一个名为 JpaRepository 的预定义类,该类提供了创建、删除、更新和从数据库表中获取数据所需的所有可能方法。

ImageGalleryRepository.java


  
  1. package com.pixeltrice.springbootimagegalleryapp.repository;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. import org.springframework.stereotype.Repository;
  4. import com.pixeltrice.springbootimagegalleryapp.entity.ImageGallery;
  5. @Repository
  6. public interface ImageGalleryRepository extends JpaRepository<ImageGallery, Long>{
  7. }

JpaRepository<ImageGallery, Long>: 在尖括号<>我们必须提到主键的实体类名和数据类型。因为在我们的例子中,实体类名是图像库,主键是具有类型的id

@Repository:此注释指示类或接口完全专用于执行各种 CRUD 操作,例如创建、更新、读取或删除数据库中的数据。

第 8 步:创建图像库服务类

ImageGalleryService.java


  
  1. package com.pixeltrice.springbootimagegalleryapp.service;
  2. import java.util.List;
  3. import java.util.Optional;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import com.pixeltrice.springbootimagegalleryapp.entity.ImageGallery;
  7. import com.pixeltrice.springbootimagegalleryapp.repository.ImageGalleryRepository;
  8. @Service
  9. public class ImageGalleryService {
  10. @Autowired
  11. private ImageGalleryRepository imageGalleryRepository;
  12. public void saveImage(ImageGallery imageGallery) {
  13. imageGalleryRepository.save(imageGallery);
  14. }
  15. public List<ImageGallery> getAllActiveImages() {
  16. return imageGalleryRepository.findAll();
  17. }
  18. public Optional<ImageGallery> getImageById(Long id) {
  19. return imageGalleryRepository.findById(id);
  20. }
  21. }

第 9 步:创建控制器类

在控制器类中,我们将创建 API,以存储和获取来自 MySQL 数据库的图像。

ImageGalleryController.java


  
  1. package com.pixeltrice.springbootimagegalleryapp.controller;
  2. import java.io.BufferedOutputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.nio.file.Paths;
  7. import java.util.Date;
  8. import java.util.List;
  9. import java.util.Optional;
  10. import javax.servlet.ServletException;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.beans.factory.annotation.Value;
  17. import org.springframework.http.HttpStatus;
  18. import org.springframework.http.ResponseEntity;
  19. import org.springframework.stereotype.Controller;
  20. import org.springframework.ui.Model;
  21. import org.springframework.web.bind.annotation.GetMapping;
  22. import org.springframework.web.bind.annotation.PathVariable;
  23. import org.springframework.web.bind.annotation.PostMapping;
  24. import org.springframework.web.bind.annotation.RequestParam;
  25. import org.springframework.web.bind.annotation.ResponseBody;
  26. import org.springframework.web.multipart.MultipartFile;
  27. import com.pixeltrice.springbootimagegalleryapp.entity.ImageGallery;
  28. import com.pixeltrice.springbootimagegalleryapp.service.ImageGalleryService;
  29. @Controller
  30. public class ImageGalleryController {
  31. @Value("${uploadDir}")
  32. private String uploadFolder;
  33. @Autowired
  34. private ImageGalleryService imageGalleryService;
  35. private final Logger log = LoggerFactory.getLogger(this.getClass());
  36. @GetMapping(value = {"/", "/home"})
  37. public String addProductPage() {
  38. return "index";
  39. }
  40. @PostMapping("/image/saveImageDetails")
  41. public @ResponseBody ResponseEntity<?> createProduct(@RequestParam("name") String name,
  42. @RequestParam("price") double price, @RequestParam("description") String description, Model model, HttpServletRequest request
  43. ,final @RequestParam("image") MultipartFile file) {
  44. try {
  45. //String uploadDirectory = System.getProperty("user.dir") + uploadFolder;
  46. String uploadDirectory = request.getServletContext().getRealPath(uploadFolder);
  47. log.info("uploadDirectory:: " + uploadDirectory);
  48. String fileName = file.getOriginalFilename();
  49. String filePath = Paths.get(uploadDirectory, fileName).toString();
  50. log.info("FileName: " + file.getOriginalFilename());
  51. if (fileName == null || fileName.contains("..")) {
  52. model.addAttribute("invalid", "Sorry! Filename contains invalid path sequence \" + fileName");
  53. return new ResponseEntity<>("Sorry! Filename contains invalid path sequence " + fileName, HttpStatus.BAD_REQUEST);
  54. }
  55. String[] names = name.split(",");
  56. String[] descriptions = description.split(",");
  57. Date createDate = new Date();
  58. log.info("Name: " + names[0]+" "+filePath);
  59. log.info("description: " + descriptions[0]);
  60. log.info("price: " + price);
  61. try {
  62. File dir = new File(uploadDirectory);
  63. if (!dir.exists()) {
  64. log.info("Folder Created");
  65. dir.mkdirs();
  66. }
  67. // Save the file locally
  68. BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
  69. stream.write(file.getBytes());
  70. stream.close();
  71. } catch (Exception e) {
  72. log.info("in catch");
  73. e.printStackTrace();
  74. }
  75. byte[] imageData = file.getBytes();
  76. ImageGallery imageGallery = new ImageGallery();
  77. imageGallery.setName(names[0]);
  78. imageGallery.setImage(imageData);
  79. imageGallery.setPrice(price);
  80. imageGallery.setDescription(descriptions[0]);
  81. imageGallery.setCreateDate(createDate);
  82. imageGalleryService.saveImage(imageGallery);
  83. log.info("HttpStatus===" + new ResponseEntity<>(HttpStatus.OK));
  84. return new ResponseEntity<>("Product Saved With File - " + fileName, HttpStatus.OK);
  85. } catch (Exception e) {
  86. e.printStackTrace();
  87. log.info("Exception: " + e);
  88. return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
  89. }
  90. }
  91. @GetMapping("/image/display/{id}")
  92. @ResponseBody
  93. void showImage(@PathVariable("id") Long id, HttpServletResponse response, Optional<ImageGallery> imageGallery)
  94. throws ServletException, IOException {
  95. log.info("Id :: " + id);
  96. imageGallery = imageGalleryService.getImageById(id);
  97. response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
  98. response.getOutputStream().write(imageGallery.get().getImage());
  99. response.getOutputStream().close();
  100. }
  101. @GetMapping("/image/imageDetails")
  102. String showProductDetails(@RequestParam("id") Long id, Optional<ImageGallery> imageGallery, Model model) {
  103. try {
  104. log.info("Id :: " + id);
  105. if (id != 0) {
  106. imageGallery = imageGalleryService.getImageById(id);
  107. log.info("products :: " + imageGallery);
  108. if (imageGallery.isPresent()) {
  109. model.addAttribute("id", imageGallery.get().getId());
  110. model.addAttribute("description", imageGallery.get().getDescription());
  111. model.addAttribute("name", imageGallery.get().getName());
  112. model.addAttribute("price", imageGallery.get().getPrice());
  113. return "imagedetails";
  114. }
  115. return "redirect:/home";
  116. }
  117. return "redirect:/home";
  118. } catch (Exception e) {
  119. e.printStackTrace();
  120. return "redirect:/home";
  121. }
  122. }
  123. @GetMapping("/image/show")
  124. String show(Model map) {
  125. List<ImageGallery> images = imageGalleryService.getAllActiveImages();
  126. map.addAttribute("images", images);
  127. return "images";
  128. }
  129. }

控制器类中存在的每个 API 的说明。

  1. @GetMapping(value = {“/”, “/home”}):每当请求到达此 API 时,它都会返回索引,由于我们已经在应用程序中实现了百里香叶,因此它将返回 index.html 页面。

2. @PostMapping(“/image/saveImageDetails”):用于将新的图像详细信息存储到MySQL数据库中。

request.getServletContext().getRealPath(uploadFolder):如您所见,我们已经通过从 application.properties 文件中分配值 /resources 来初始化变量 uploadFolder

我们将参数传递给 getRealPath(),因此它将返回您在本地系统中创建工作区的完整路径。因此对我来说

file.getOriginal文件名():它将返回产品图片的实际名称,例如image.png,这取决于您上传的产品名称。

Paths.get(uploadDirectory, fileName).toString():它将返回系统上保存上传图像的确切位置。

之后,我们将图像转换为字节数组,并将所有与图像相关的详细信息(例如名称,描述,图像等)存储到MySQL数据库中。

如您所见,我们将图像以 byte[] 形式存储在数据库表中,这就是为什么在实体类中我们必须使用注释@Lob

3. @GetMapping(“/image/display/{id}”):该接口用于从数据库中获取特定图像的 byte[] 形式,并将其转换为 jpeg、png、jpg 或 gif 格式以显示在浏览器中。

4. @GetMapping(“/image/imageDetails”):它根据镜像 ID 从数据库中获取镜像详情,并显示在镜像详情中.html

5. @GetMapping(“/image/show”):这是控制器类中的最后一个API,用于在images.html页面中显示产品列表及其详细信息。

第 10 步:创建 HTML 页面

在最后一步中,我们看到我们的应用程序需要三个 HTML 页面。让我们创建它。

注意:确保你应该在\src\main\resources\templates中创建所有HTML页面

index.html


  
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>PixelTrice</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  8. <link rel="stylesheet" href="/css/style.css">
  9. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  10. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  11. </head>
  12. <body>
  13. <br><br>
  14. <h1 class="text-center">Spring Boot Image Gallery Application</h1><br><br>
  15. <div class="contact py-sm-5 py-4">
  16. <div class="container py-xl-4 py-lg-2">
  17. <!-- form -->
  18. <form id="form">
  19. <div class="contact-grids1 w3agile-6">
  20. <div class="row">
  21. <div class="col-md-6 col-sm-6 contact-form1 form-group">
  22. <label class="col-form-label">Name</label>
  23. <input type="text" class="form-control" placeholder="Product Name" id="name" name="name" required="required">
  24. <p id="error_name"></p>
  25. </div>
  26. <div class="col-md-6 col-sm-6 contact-form1 form-group">
  27. <label class="col-form-label">Description</label>
  28. <textarea class="form-control" placeholder="Product Description" id="description" rows="3" cols="45" name="description" required="required"></textarea>
  29. <p id="error_description"></p>
  30. </div>
  31. <div class="col-md-6 col-sm-6 contact-form1 form-group">
  32. <label class="col-form-label">Image</label>
  33. <input type="file" class="form-control" placeholder="" name="image" id="image" required="required">
  34. <p id="error_file"></p>
  35. </div>
  36. <div class="col-md-6 col-sm-6 contact-form1 form-group">
  37. <label class="col-form-label">Price</label>
  38. <input type="text" class="form-control" placeholder="Price" name="price" id="price" required="required">
  39. <p id="error_price"></p>
  40. </div>
  41. </div>
  42. <div class="right-w3l col-md-6">
  43. <input type="button" id="submit" class="btn btn-primary form-control" value="Submit">
  44. <br><br>
  45. </div>
  46. <a href="/image/show" style="float:left;" class="btn btn-success text-right">Show All</a>
  47. </div>
  48. <br>
  49. <div id="success" class="text-center" style="color:green;"></div>
  50. <div id="error" class="text-center" style="color:red;"></div>
  51. </form>
  52. </div>
  53. </div>
  54. <p class="text-center">
  55. <img src="/images/loader.gif" alt="loader" style="width: 150px;height: 120px;" id="loader">
  56. </p>
  57. <script src="/js/product.js"></script>
  58. </body>
  59. </html>

images.html


  
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <title>PixelTrice</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  8. <link rel="stylesheet" href="/css/style.css">
  9. <link rel="stylesheet" href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap.min.css">
  10. </head>
  11. <body>
  12. <br>
  13. <h1 class="text-center">Spring Boot Image Gallery Application
  14. <a href="/home" class="btn btn-danger text-right">Go Home</a>
  15. </h1>
  16. <br><br>
  17. <table id="example" class="table table-striped table-bordered text-center">
  18. <thead>
  19. <tr>
  20. <th>SR. No.</th>
  21. <th>Name</th>
  22. <th>Image</th>
  23. <th>Description</th>
  24. <th>Price</th>
  25. <th>Created date</th>
  26. <th>Action</th>
  27. </tr>
  28. </thead>
  29. <tbody th:with="count=0">
  30. <tr th:each = "imageGallery, hh : ${images}">
  31. <td th:with="count=${count + 1}" th:text="${count}"></td>
  32. <td th:text="${imageGallery.name}"></td>
  33. <td><img th:src="@{${'/image/display/'+ imageGallery.id}}"
  34. class="card img-fluid" style="width:300px" alt=""/></td>
  35. <td th:text="${imageGallery.description}"></td>
  36. <td th:text="${imageGallery.price}"></td>
  37. <td th:text="${#dates.format({imageGallery.createDate}, 'dd-MM-yyyy')}"/></td>
  38. <td><a th:href="@{/image/imageDetails(id=${imageGallery.id})}" class="btn btn-info text-right" target="_blank">View</a></td>
  39. </tr>
  40. </tbody>
  41. </table>
  42. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  43. <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
  44. <script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap.min.js"></script>
  45. <script type="text/javascript">
  46. $(document).ready(function() {
  47. $('#example').DataTable();
  48. } );
  49. </script>
  50. </body>
  51. </html>

imagedetails.html


  
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="ISO-8859-1">
  5. <title>PixelTrice</title>
  6. <meta charset="utf-8">
  7. <meta name="viewport" content="width=device-width, initial-scale=1">
  8. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  9. <link rel="stylesheet" href="/css/style.css">
  10. </head>
  11. <body>
  12. <br>
  13. <div class="banner-bootom-w3-agileits py-5">
  14. <div class="container py-xl-4 py-lg-2">
  15. <!-- tittle heading -->
  16. <h3 class="tittle-w3l text-center mb-lg-5 mb-sm-4 mb-3">
  17. <span>I</span>mage
  18. <span>D</span>etails</h3><br>
  19. <!-- //tittle heading -->
  20. <div class="row">
  21. <div class="col-lg-5 col-md-8 single-right-left ">
  22. <div class="grid images_3_of_2">
  23. <div class="flexslider">
  24. <div class="thumb-image">
  25. <img th:src="@{${'/image/display/'+id}}"
  26. class="img img-responsive img-fluid" alt="">
  27. </div>
  28. <div class="clearfix"></div>
  29. </div>
  30. </div>
  31. </div>
  32. <div class="col-lg-7 single-right-left simpleCart_shelfItem">
  33. Name: <span th:text="${name}" class="mb-3"></span>
  34. <p class="mb-3">
  35. Price :&#36; <span class="item_price" th:text="${price}"></span>
  36. </p>
  37. <div class="product-single-w3l">
  38. Description: <span th:text="${description}" class="my-sm-4 my-3">
  39. </span>
  40. </div><br>
  41. <a href="/image/show">Go Back</a>
  42. &emsp;<a href="/">Go Home</a>
  43. </div>
  44. </div>
  45. </div>
  46. </div>
  47. </body>
  48. </html>

第 11 步:创建 css 和 javascript 文件

在此步骤中,我们将为我们的应用程序创建样式.css产品.js。还在图像文件夹中放置了一个加载图像。

确保你应该在 src\main\resources\static\css 和 product.js 在路径 src\main\resources\static\js 中创建 style.css

注意我们需要在路径 src\main\resources 上再创建一个包含命名图像的文件夹,我们必须在其中存储加载图像 您可以从我的 GitHub 帐户上提供的源代码下载它。

product.js


  
  1. $(document).ready(function() {
  2. $('#loader').hide();
  3. $("#submit").on("click", function() {
  4. $("#submit").prop("disabled", true);
  5. var name = $("#name").val();
  6. var file = $("#image").val();
  7. var price = $("#price").val();
  8. var description = $("#description").val();
  9. var form = $("#form").serialize();
  10. var data = new FormData($("#form")[0]);
  11. data.append('name', name);
  12. data.append('price', price);
  13. data.append('description', description);
  14. //alert(data);
  15. $('#loader').show();
  16. if (name === "" || file === "" || price === "" || description === "") {
  17. $("#submit").prop("disabled", false);
  18. $('#loader').hide();
  19. $("#name").css("border-color", "red");
  20. $("#image").css("border-color", "red");
  21. $("#price").css("border-color", "red");
  22. $("#description").css("border-color", "red");
  23. $("#error_name").html("Please fill the required field.");
  24. $("#error_file").html("Please fill the required field.");
  25. $("#error_price").html("Please fill the required field.");
  26. $("#error_description").html("Please fill the required field.");
  27. } else {
  28. $("#name").css("border-color", "");
  29. $("#image").css("border-color", "");
  30. $("#price").css("border-color", "");
  31. $("#description").css("border-color", "");
  32. $('#error_name').css('opacity', 0);
  33. $('#error_file').css('opacity', 0);
  34. $('#error_price').css('opacity', 0);
  35. $('#error_description').css('opacity', 0);
  36. $.ajax({
  37. type: 'POST',
  38. enctype: 'multipart/form-data',
  39. data: data,
  40. url: "/image/saveImageDetails",
  41. processData: false,
  42. contentType: false,
  43. cache: false,
  44. success: function(data, statusText, xhr) {
  45. console.log(xhr.status);
  46. if(xhr.status == "200") {
  47. $('#loader').hide();
  48. $("#form")[0].reset();
  49. $('#success').css('display','block');
  50. $("#error").text("");
  51. $("#success").html("Product Inserted Succsessfully.");
  52. $('#success').delay(2000).fadeOut('slow');
  53. }
  54. },
  55. error: function(e) {
  56. $('#loader').hide();
  57. $('#error').css('display','block');
  58. $("#error").html("Oops! something went wrong.");
  59. $('#error').delay(5000).fadeOut('slow');
  60. location.reload();
  61. }
  62. });
  63. }
  64. });
  65. });

注意:请参考我的Github帐户了解样式.css代码。

现在我们可以运行应用程序了,但在此之前,请确保您提供了正确的 MySQL 用户名、密码和架构名称。

还要验证文件夹结构,如图所示。

第 12 步:运行应用程序

运行应用程序后,添加图像详细信息和视图,如图所示。

进入本地主机:8080上传图片,如图所示。

按提交按钮将图像详细信息存储在MySQL数据库中。点击 全部显示 按钮查看图像。

 

单击“查看”按钮以查看图像的详细信息。

 

下载源代码

总结

在本教程中,我们学习并构建了使用 MySQL、Thymeleaf 和 Spring Boot Framework 上传、存储和查看图像的应用程序。源代码在我的 Github 帐户上可用,如果卡在任何地方或遇到一些错误,请通过它。您也可以在下面的评论部分提出任何疑问。


转载:https://blog.csdn.net/allway2/article/details/128241813
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场