SpringBoot文件上传到数据库

首先导入了相应的jar包


<dependency>
    <groupId>org.thymeleafgroupId>
    <artifactId>thymeleaf-spring5artifactId>
dependency>
<dependency>
    <groupId>org.thymeleaf.extrasgroupId>
    <artifactId>thymeleaf-extras-java8timeartifactId>
dependency>


<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
dependency>


<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.1.2version>
dependency>


<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.22version>
dependency>

对数据源,mybatis,和上传文件进行配置

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: shw123zxc
    url: jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
  servlet:
    multipart:
      max-request-size: 10MB   #上传文件的最大总大小
      max-file-size: 10MB		#上传单个文件的最大大小
mybatis:
  type-aliases-package: cn.codewei.pojo
  mapper-locations: classpath:/mapper/*.xml

然后写一个文件上传的html,注意表单的==enctype属性要设置为multipart/form-data==


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h1>文件上传h1>
    <form method="post" enctype="multipart/form-data" action="/upload">
        <input type="file" name="file">
        <input type="submit" value="上传">
    form>
body>
html>

然后写一个Mapper和对应的Mapper.xml和service

@Mapper
@Repository
public interface PhotoMapper {
    // 向数据库中添加图片
    public int addPhoto(Photo photo);

    // 从数据库中取出图片
    public Photo getPhotoById(@Param("id") int id);
}


<mapper namespace="cn.codewei.mapper.PhotoMapper">
    <insert id="addPhoto" parameterType="photo">
        insert into image values (#{id},#{photo},#{photo_name},#{photo_type})
    insert>
    <select id="getPhotoById" resultType="photo">
        select * from image where id=#{id}
    select>
mapper>

在Controller中进行调用

上传

@Autowired
private PhotoService photoService;

@Autowired
private Photo photo;

@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
    byte[] bytes = file.getBytes();
    photo.setPhoto(bytes);
    photo.setPhoto_name(file.getOriginalFilename());
    photo.setPhoto_type(".jpg");

    photoService.addPhoto(photo);

    return "上传成功!";
}

取出,在页面中显示

@RequestMapping("/getPhoto")
public String getImage(HttpServletResponse response) throws IOException {
    Photo photo = photoService.getPhotoById(1);
    byte[] photo1 = photo.getPhoto();
    ServletOutputStream os = response.getOutputStream();
    os.write(photo1);
    os.close();
    return "";
}

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <h1>首页h1>
    <img src="/getPhoto" width="200px" height="200px">
body>
html>

你可能感兴趣的:(java框架)