SpringBoot整合springDataJpa实现图片上传和显示

目录

  • 使用工具
  • 使用说明
  • 使用maven的pom.xml文件
  • 环境搭建
  • 代码示例
    • SQL代码
    • java目录
            • Img.java
            • MyWebMvcConfigurerAdapter.java
            • FileController.java
            • ImgDao.java
            • imgServiceImpl.java
            • ImgService.java
            • App.java
    • resources目录
            • index.html
            • application.yml
    • test目录
            • AppTest.java
  • 效果展示

使用工具

IDEA2018.2 MySQL5.6 JDK1.8

使用说明

需要在数据库中创建一个数据库,无需创建数据库表
SpringDtataJpa自动生成数据表

使用maven的pom.xml文件



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>com.gitee.vvcatgroupId>
  <artifactId>picture_uploadartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>jarpackaging>


  <name>picture_uploadname>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.7.RELEASEversion>
        <relativePath/> 
    parent>

  <properties>
      <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
      <project.version>0.0.1-SNAPSHOTproject.version>
      <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
      <java.version>1.8java.version>
  properties>

  <dependencies>
      
      <dependency>
          <groupId>org.springframework.bootgroupId>
          <artifactId>spring-boot-starter-data-jpaartifactId>
      dependency>
      <dependency>
          <groupId>org.springframework.bootgroupId>
          <artifactId>spring-boot-starter-jdbcartifactId>
      dependency>
      
      <dependency>
          <groupId>org.springframework.bootgroupId>
          <artifactId>spring-boot-starter-testartifactId>
          <scope>testscope>
      dependency>

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

      
      
      <dependency>
          <groupId>org.springframework.bootgroupId>
          <artifactId>spring-boot-starter-webartifactId>
      dependency>

      
      <dependency>
          <groupId>org.springframework.bootgroupId>
          <artifactId>spring-boot-starter-thymeleafartifactId>
      dependency>

  dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-maven-pluginartifactId>
      plugin>
    plugins>
  build>
project>

环境搭建

SpringBoot整合springDataJpa实现图片上传和显示_第1张图片
SpringBoot整合springDataJpa实现图片上传和显示_第2张图片

代码示例

SQL代码

CREATE DATABASE vvcat;
USE vvcat;
CREATE TABLE `img` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

java目录

Img.java
package com.gitee.vvcat.bean;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * @Author ꧁ʚVVcatɞ꧂
 * @Date 2019/11/12 11:34
 * @Version 1.0
 **/
@Entity(name = "img")
public class Img {

    @Id
    @GeneratedValue
    private Integer id;

    private String url;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
MyWebMvcConfigurerAdapter.java
package com.gitee.vvcat.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @Author ꧁ʚVVcatɞ꧂
 * @Date 2019/11/12 11:32
 * @Version 1.0
 **/
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        //指向外部目录
        registry.addResourceHandler("img//**").addResourceLocations("file:E:/img/");
        super.addResourceHandlers(registry);
    }
}
FileController.java
package com.gitee.vvcat.controller;

import com.gitee.vvcat.bean.Img;
import com.gitee.vvcat.service.ImgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author ꧁ʚVVcatɞ꧂
 * @Date 2019/11/12 11:32
 * @Version 1.0
 **/
@Controller
public class FileController {
    @Autowired
    private ImgService imgService;

    @Value("${com.vvcat}")
    //获取主机端口
    private String post;
    //获取本机ip
    private String host;
    //图片存放根路径
    private String rootPath = "E:";
    //图片存放根目录下的子目录
    private String sonPath = "/img/";
    //获取图片链接
    private String imgPath;

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);


    @GetMapping("/")
    public String index(Model model,HttpServletRequest httpServletRequest){
        String imgPath = (String) httpServletRequest.getSession().getAttribute("imgPath");
        System.out.println("index:" + imgPath);
        model.addAttribute("imgPath",imgPath);
        return "index";
    }

    @RequestMapping(value = "upload")
    @ResponseBody
    public String upload(@RequestParam("test") MultipartFile file, HttpServletRequest httpServletRequest) {
        //返回上传的文件是否为空,即没有选择任何文件,或者所选文件没有内容。
        //防止上传空文件导致奔溃
        if (file.isEmpty()) {
            return "文件为空";
        }

        //获取本机IP
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("get server host Exception e:", e);
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        //logger.info("上传的文件名为:" + fileName);
        // 设置文件上传后的路径
        String filePath = rootPath + sonPath;
        logger.info("上传的文件路径" + filePath);
        logger.info("整个图片路径:" + host + ":" + post + sonPath + fileName);
        //创建文件路径
        File dest = new File(filePath + fileName);

        String imgPath = ("http://" + host + ":" + post + sonPath + fileName).toString();

        // 解决中文问题,liunx下中文路径,图片显示问题
        // fileName = UUID.randomUUID() + suffixName;

        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            //假如文件不存在即重新创建新的文件已防止异常发生
            dest.getParentFile().mkdirs();
        }
        try {
            //transferTo(dest)方法将上传文件写到服务器上指定的文件
            file.transferTo(dest);
            //将链接保存到URL中
            Img imgTest = imgService.add(new Img(), imgPath);
            HttpSession session = httpServletRequest.getSession();//import javax.servlet.http.HttpSession;
            session.setAttribute("imgPath",imgPath);
            return "上传成功";
        } catch (Exception e) {
            return "上传失败";
        }
    }
}
ImgDao.java
package com.gitee.vvcat.repository;

import com.gitee.vvcat.bean.Img;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @Author ꧁ʚVVcatɞ꧂
 * @Date 2019/11/12 11:35
 * @Version 1.0
 **/
public interface ImgDao extends JpaRepository<Img,Integer> {
}
imgServiceImpl.java
package com.gitee.vvcat.service.impl;

import com.gitee.vvcat.bean.Img;
import com.gitee.vvcat.repository.ImgDao;
import com.gitee.vvcat.service.ImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author ꧁ʚVVcatɞ꧂
 * @Date 2019/11/12 11:37
 * @Version 1.0
 **/
@Service
public class imgServiceImpl implements ImgService {

    @Autowired
    private ImgDao imgDao;

    @Override
    public Img add(Img img, String path) {
        img.setUrl(path);
        return imgDao.save(img);
    }
}
ImgService.java
package com.gitee.vvcat.service;

import com.gitee.vvcat.bean.Img;

/**
 * @Author ꧁ʚVVcatɞ꧂
 * @Date 2019/11/12 11:36
 * @Version 1.0
 **/
public interface ImgService {
    /**
     * 添加图片地址
     * @param
     * @return
     */
    Img add(Img img, String path);
}
App.java
package com.gitee.vvcat;

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

/**
 * Hello world!
 *
 */
@SpringBootApplication
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
    }
}

resources目录

index.html

<html lang="en" xmlns:th="http://www.thymeleaf.org"  >
<head>
    <title>上传图片title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
head>
<body>
<div th:if="${imgPath != null}">
    <img th:src="${imgPath}">
div>
<form action="/upload" method="POST" enctype="multipart/form-data">
    文件:<input type="file" name="test"/>
    <input type="submit" value="上传"/>
form>

body>
html>
application.yml
server:
  port: 8080

spring:
  http:
    encoding:
      force: true
      charset: UTF-8
    thymeleaf:
      cache: false
      check-template-location: true
      content-type: text/html; charset=utf-8
      enabled: true
      encoding: UTF-8
      prefix: classpath:/templates/
      suffix: .html
      mode: LEGACYHTML5

  datasource:
    url: jdbc:mysql://localhost:3306/vvcat?characterEncoding=utf-8&serverTimezone=GMT%2B8
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true



com:
  vvcat: ${server.port}

test目录

AppTest.java
package com.gitee.vvcat;

import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * Unit test for simple App.
 */
@SpringBootTest
public class AppTest 
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue()
    {
        System.out.println("hello world");
    }
}

效果展示

  1. 首页
    SpringBoot整合springDataJpa实现图片上传和显示_第3张图片
  2. 可点击选择文件进行文件上传
    SpringBoot整合springDataJpa实现图片上传和显示_第4张图片
  3. 选择完成后点击上传
    SpringBoot整合springDataJpa实现图片上传和显示_第5张图片
  4. 数据库已经插入图片保存路径
    在这里插入图片描述
  5. 图片在硬盘中的存储位置
    SpringBoot整合springDataJpa实现图片上传和显示_第6张图片
    6.在网页显示图片 再次 访问 localhost:8080端口 可显示图片
    SpringBoot整合springDataJpa实现图片上传和显示_第7张图片
  6. 如果图片上传为空
    SpringBoot整合springDataJpa实现图片上传和显示_第8张图片

你可能感兴趣的:(Java)