当前位置:   article > 正文

使用Springboot上传图片并将URL保存到数据库中_springboot项目存入数据库的是图片本身还是url

springboot项目存入数据库的是图片本身还是url

背景:之前一直想做上传图片如何将图片保存到服务器路径下面并将URL地址保存到数据库中,在网上找了很多大多都是五五开,有幸找到一篇简单的上传图片教程,并对其加以改正,得到了自己想要的效果。

参考博主链接:https://blog.csdn.net/Coding13/article/details/54577076

废话不多说,先将我自己项目的整体结构展示一下

  1.   使用环境 idea + Maven + JDK1.8
  2.   pom.xml配置
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0</modelVersion>
    5. <parent>
    6. <groupId>org.springframework.boot</groupId>
    7. <artifactId>spring-boot-starter-parent</artifactId>
    8. <version>2.0.1.RELEASE</version>
    9. <relativePath/> <!-- lookup parent from repository -->
    10. </parent>
    11. <groupId>com.library</groupId>
    12. <artifactId>nbt</artifactId>
    13. <version>0.0.1-SNAPSHOT</version>
    14. <name>nbt</name>
    15. <description>Demo project for Spring Boot</description>
    16. <properties>
    17. <java.version>1.8</java.version>
    18. </properties>
    19. <dependencies>
    20. <dependency>
    21. <groupId>org.springframework.boot</groupId>
    22. <artifactId>spring-boot-starter-web</artifactId>
    23. </dependency>
    24. <dependency>
    25. <groupId>org.mybatis.spring.boot</groupId>
    26. <artifactId>mybatis-spring-boot-starter</artifactId>
    27. <version>2.0.0</version>
    28. </dependency>
    29. <!--<dependency>-->
    30. <!--<groupId>mysql</groupId>-->
    31. <!--<artifactId>mysql-connector-java</artifactId>-->
    32. <!--<version>5.1.25</version>-->
    33. <!--</dependency> -->
    34. <dependency>
    35. <groupId>mysql</groupId>
    36. <artifactId>mysql-connector-java</artifactId>
    37. <version>8.0.15</version>
    38. </dependency>
    39. <dependency>
    40. <groupId>org.springframework.boot</groupId>
    41. <artifactId>spring-boot-starter-test</artifactId>
    42. <scope>test</scope>
    43. </dependency>
    44. <dependency>
    45. <groupId>org.springframework.boot</groupId>
    46. <artifactId>spring-boot-starter-data-jpa</artifactId>
    47. </dependency>
    48. <dependency>
    49. <groupId>com.alibaba</groupId>
    50. <artifactId>druid</artifactId>
    51. <version>1.1.9</version>
    52. </dependency>
    53. <dependency>
    54. <groupId>com.alibaba</groupId>
    55. <artifactId>fastjson</artifactId>
    56. <version>1.2.44</version>
    57. </dependency>
    58. <dependency>
    59. <groupId>io.springfox</groupId>
    60. <artifactId>springfox-swagger2</artifactId>
    61. <version>2.2.2</version>
    62. </dependency>
    63. <dependency>
    64. <groupId>io.springfox</groupId>
    65. <artifactId>springfox-swagger-ui</artifactId>
    66. <version>2.2.2</version>
    67. </dependency>
    68. <dependency>
    69. <groupId>cn.hutool</groupId>
    70. <artifactId>hutool-all</artifactId>
    71. <version>4.1.14</version>
    72. </dependency>
    73. </dependencies>
    74. <build>
    75. <!--放置在dao下的话要在这里配置,让springboot启动时去扫描-->
    76. <resources>
    77. <resource>
    78. <directory>${basedir}/src/main/java</directory>
    79. <includes>
    80. <include>**/*.xml</include>
    81. </includes>
    82. </resource>
    83. <resource>
    84. <directory>src/main/resources</directory>
    85. <includes>
    86. <include>**/*.yml</include>
    87. <include>**/*.properties</include>
    88. <include>**/log/**/logback.xml</include>
    89. </includes>
    90. </resource>
    91. </resources>
    92. <plugins>
    93. <plugin>
    94. <groupId>org.springframework.boot</groupId>
    95. <artifactId>spring-boot-maven-plugin</artifactId>
    96. </plugin>
    97. <!-- mybatis generator 自动生成代码插件 -->
    98. <plugin>
    99. <groupId>org.mybatis.generator</groupId>
    100. <artifactId>mybatis-generator-maven-plugin</artifactId>
    101. <version>1.3.2</version>
    102. <configuration>
    103. <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
    104. <overwrite>true</overwrite>
    105. <verbose>true</verbose>
    106. </configuration>
    107. </plugin>
    108. </plugins>
    109. </build>
    110. </project>
  3. 控制层核心代码
    1. package com.library.nbt.controller;
    2. import com.library.nbt.utils.VerifyUtil;
    3. import io.swagger.annotations.Api;
    4. import io.swagger.annotations.ApiOperation;
    5. import io.swagger.annotations.ApiResponse;
    6. import io.swagger.annotations.ApiResponses;
    7. import org.springframework.web.bind.annotation.GetMapping;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.RequestMethod;
    10. import org.springframework.web.bind.annotation.RestController;
    11. import javax.imageio.ImageIO;
    12. import javax.servlet.http.HttpServletRequest;
    13. import javax.servlet.http.HttpServletResponse;
    14. import javax.servlet.http.HttpSession;
    15. import java.awt.image.BufferedImage;
    16. import java.io.OutputStream;
    17. @RestController
    18. @RequestMapping(value = "/api")
    19. @Api(value = "验证码接口", tags = "验证码接口", description = "")
    20. public class CodeController {
    21. @ApiOperation(value = "生成验证码", notes = "生成验证码")
    22. @ApiResponses(value = {
    23. @ApiResponse(code = 200, message = "successful request"),
    24. @ApiResponse(code = 500, message = "internal server error")})
    25. @RequestMapping(value = "/v1/getcode", method = RequestMethod.GET)
    26. public void getCode(HttpServletResponse response, HttpServletRequest request) throws Exception {
    27. HttpSession session = request.getSession();
    28. //利用图片工具生成图片
    29. //第一个参数是生成的验证码,第二个参数是生成的图片
    30. Object[] objs = VerifyUtil.createImage();
    31. //将验证码存入Session
    32. session.setAttribute("imageCode", objs[0]);
    33. //将图片输出给浏览器
    34. BufferedImage image = (BufferedImage) objs[1];
    35. response.setContentType("image/png");
    36. OutputStream os = response.getOutputStream();
    37. ImageIO.write(image, "png", os);
    38. }
    39. }

     

  4. application.yml配置
    1. server.port=12000
    2. ##jdbc配置 mysql 8.1以上版本
    3. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    4. spring.datasource.url=jdbc:mysql://localhost:3306/btn-dev
    5. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    6. spring.datasource.username=root
    7. spring.datasource.password=123456
    8. ##jdbc配置 mysql 8.1以下版本
    9. #spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    10. #spring.datasource.url=jdbc:mysql://localhost:3306/btn
    11. #spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    12. #spring.datasource.username=root
    13. #spring.datasource.password=123456
    14. ## 该配置节点为独立的节点,有容易将这个配置放在spring的节点下,导致配置无法被识别
    15. #注意:一定要对应mapper映射xml文件的所在路径
    16. mybatis.mapper-locations=classpath:com/library/nbt/dao/**/mapper/*.xml
    17. mybatis.type-aliases-package=com.library.nbt.model.entity
    18. #配置generatorConfig.xml 运行时:mybatis-generator:generate -e
    19. db.driverLocation=D:\\Interest\\mybatis-generator-core-1.3.2\\lib\\mysql-connector-java-8.0.12.jar
    20. #本地浏览器地址
    21. spring.web.googleexcute=explorer
    22. #要打开的网址
    23. spring.web.loginurl=http://localhost:${server.port}/swagger-ui.html
    24. #是否要启动时打开浏览器
    25. spring.web.isopenurl=true
    26. logging.config=classpath:log/dev/logback.xml
    27. file.rootPath=E:
    28. file.sonPath=/img/

     

  5. 配置类
    1. package com.library.nbt.config;
    2. import org.springframework.beans.factory.annotation.Value;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    6. @Configuration
    7. public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    8. //图片存放根路径
    9. @Value("${file.rootPath}")
    10. private String ROOT_PATH;
    11. //图片存放根目录下的子目录
    12. @Value("${file.sonPath}")
    13. private String SON_PATH;
    14. @Override
    15. public void addResourceHandlers(ResourceHandlerRegistry registry){
    16. String filePath = "file:" + ROOT_PATH + SON_PATH;
    17. //指向外部目录
    18. registry.addResourceHandler("img//**").addResourceLocations(filePath);
    19. super.addResourceHandlers(registry);
    20. }
    21. }

     

  6. service层及实现类
    1. package com.library.nbt.service;
    2. import org.springframework.web.multipart.MultipartFile;
    3. public interface UploadFileService {
    4. String getUploadFilePath(MultipartFile file);
    5. }
    1. package com.library.nbt.service.impl;
    2. import com.library.nbt.dao.UplocalFileEntityMapper;
    3. import com.library.nbt.model.entity.UplocalFileEntity;
    4. import com.library.nbt.service.UploadFileService;
    5. import com.library.nbt.utils.DateUtils;
    6. import org.slf4j.Logger;
    7. import org.slf4j.LoggerFactory;
    8. import org.springframework.beans.factory.annotation.Autowired;
    9. import org.springframework.beans.factory.annotation.Value;
    10. import org.springframework.stereotype.Service;
    11. import org.springframework.web.multipart.MultipartFile;
    12. import java.io.File;
    13. import java.net.InetAddress;
    14. import java.net.UnknownHostException;
    15. import java.util.Random;
    16. @Service
    17. public class UploadFileServiceImpl implements UploadFileService {
    18. private static final Logger LOG = LoggerFactory.getLogger(UploadFileServiceImpl.class);
    19. //图片存放根路径
    20. @Value("${file.rootPath}")
    21. private String ROOT_PATH;
    22. //图片存放根目录下的子目录
    23. @Value("${file.sonPath}")
    24. private String SON_PATH;
    25. @Value("${server.port}")
    26. //获取主机端口
    27. private String POST;
    28. @Autowired
    29. private UplocalFileEntityMapper uplocalFileEntityMapper;
    30. @Override
    31. public String getUploadFilePath(MultipartFile file) {
    32. //返回上传的文件是否为空,即没有选择任何文件,或者所选文件没有内容。
    33. //防止上传空文件导致奔溃
    34. if (file.isEmpty()) {
    35. throw new NullPointerException("文件为空");
    36. }
    37. // 设置文件上传后的路径
    38. String filePath = ROOT_PATH + SON_PATH;
    39. // 获取文件名后缀名
    40. String suffix = file.getOriginalFilename();
    41. String prefix = suffix.substring(suffix.lastIndexOf(".")+1);
    42. //为防止文件重名被覆盖,文件名取名为:当前日期 + 1-1000内随机数
    43. Random random = new Random();
    44. Integer randomFileName = random.nextInt(1000);
    45. String fileName = DateUtils.timeStamp2Date(String.valueOf(System.currentTimeMillis() /100),"yyyyMMddHHmmss") + randomFileName +"." + prefix;
    46. //创建文件路径
    47. File dest = new File(filePath + fileName);
    48. // 解决中文问题,liunx下中文路径,图片显示问题
    49. // fileName = UUID.randomUUID() + suffixName;
    50. // 检测是否存在目录
    51. if (!dest.getParentFile().exists()) {
    52. //假如文件不存在即重新创建新的文件已防止异常发生
    53. dest.getParentFile().mkdirs();
    54. }
    55. try {
    56. //transferTo(dest)方法将上传文件写到服务器上指定的文件
    57. file.transferTo(dest);
    58. //保存t_upload_file表中
    59. String filePathNew = SON_PATH + fileName;
    60. String profilePhoto = saveUploadFile(filePathNew);
    61. System.out.println(profilePhoto);
    62. return profilePhoto;
    63. } catch (Exception e) {
    64. return dest.toString();
    65. }
    66. }
    67. private String saveUploadFile(String filePathNew) {
    68. //获取本机IP
    69. String host = null;
    70. try {
    71. host = InetAddress.getLocalHost().getHostAddress();
    72. } catch (UnknownHostException e) {
    73. LOG.error("get server host Exception e:", e);
    74. }
    75. UplocalFileEntity uplocalFileEntity = new UplocalFileEntity();
    76. uplocalFileEntity.setCreateTime(System.currentTimeMillis());
    77. uplocalFileEntity.setUpdateTime(System.currentTimeMillis());
    78. uplocalFileEntity.setEnabled(1);
    79. uplocalFileEntity.setProfilePhoto(host + ":" + POST + filePathNew);
    80. Integer result = uplocalFileEntityMapper.insertSelective(uplocalFileEntity);
    81. System.out.println("插入了" + result + "数据");
    82. System.out.println("uplocalFileEntity.getProfilePhoto():" + uplocalFileEntity.getProfilePhoto());
    83. return uplocalFileEntity.getProfilePhoto();
    84. }
    85. }

     

  7. mapper层及实现
    1. package com.library.nbt.dao;
    2. import com.library.nbt.model.entity.UplocalFileEntity;
    3. import org.apache.ibatis.annotations.Mapper;
    4. @Mapper
    5. public interface UplocalFileEntityMapper {
    6. /**
    7. * This method was generated by MyBatis Generator.
    8. * This method corresponds to the database table t_uplocal_file
    9. *
    10. * @mbggenerated
    11. */
    12. int insert(UplocalFileEntity record);
    13. /**
    14. * This method was generated by MyBatis Generator.
    15. * This method corresponds to the database table t_uplocal_file
    16. *
    17. * @mbggenerated
    18. */
    19. int insertSelective(UplocalFileEntity record);
    20. }
    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    3. <mapper namespace="com.library.nbt.dao.UplocalFileEntityMapper" >
    4. <resultMap id="BaseResultMap" type="com.library.nbt.model.entity.UplocalFileEntity" >
    5. <!--
    6. WARNING - @mbggenerated
    7. This element is automatically generated by MyBatis Generator, do not modify.
    8. -->
    9. <result column="id" property="id" jdbcType="INTEGER" />
    10. <result column="create_time" property="createTime" jdbcType="BIGINT" />
    11. <result column="update_time" property="updateTime" jdbcType="BIGINT" />
    12. <result column="enabled" property="enabled" jdbcType="INTEGER" />
    13. <result column="profile_photo" property="profilePhoto" jdbcType="VARCHAR" />
    14. </resultMap>
    15. <insert id="insert" parameterType="com.library.nbt.model.entity.UplocalFileEntity" >
    16. <!--
    17. WARNING - @mbggenerated
    18. This element is automatically generated by MyBatis Generator, do not modify.
    19. -->
    20. <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
    21. SELECT LAST_INSERT_ID()
    22. </selectKey>
    23. insert into t_uplocal_file (create_time, update_time, enabled,
    24. profile_photo)
    25. values (#{createTime,jdbcType=BIGINT}, #{updateTime,jdbcType=BIGINT}, #{enabled,jdbcType=INTEGER},
    26. #{profilePhoto,jdbcType=VARCHAR})
    27. </insert>
    28. <insert id="insertSelective" parameterType="com.library.nbt.model.entity.UplocalFileEntity" >
    29. <!--
    30. WARNING - @mbggenerated
    31. This element is automatically generated by MyBatis Generator, do not modify.
    32. -->
    33. <selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
    34. SELECT LAST_INSERT_ID()
    35. </selectKey>
    36. insert into t_uplocal_file
    37. <trim prefix="(" suffix=")" suffixOverrides="," >
    38. <if test="createTime != null" >
    39. create_time,
    40. </if>
    41. <if test="updateTime != null" >
    42. update_time,
    43. </if>
    44. <if test="enabled != null" >
    45. enabled,
    46. </if>
    47. <if test="profilePhoto != null" >
    48. profile_photo,
    49. </if>
    50. </trim>
    51. <trim prefix="values (" suffix=")" suffixOverrides="," >
    52. <if test="createTime != null" >
    53. #{createTime,jdbcType=BIGINT},
    54. </if>
    55. <if test="updateTime != null" >
    56. #{updateTime,jdbcType=BIGINT},
    57. </if>
    58. <if test="enabled != null" >
    59. #{enabled,jdbcType=INTEGER},
    60. </if>
    61. <if test="profilePhoto != null" >
    62. #{profilePhoto,jdbcType=VARCHAR},
    63. </if>
    64. </trim>
    65. </insert>
    66. </mapper>

     

  8. 进行测试,我用的是SwaggerUI,如果没有安装的话可以下载Postman进行接口测试

 

url也保存到数据库中了,复制URL地址在网页打开即可访问

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/845778
推荐阅读
相关标签
  

闽ICP备14008679号