关于Springboot在新增和修改下上传图片并显示的问题

解决的问题:

本篇文章除了解决上传图片并显示的问题,还有就是在新增和修改下的图片上传如何处理。在这里新增和修改的页面是同一页面,修改的时候,将会把值带过去,但是由于类型为file的input标签是不能给其赋值的,那么若不改变原来图片,但是input标签中又没有值,这时怎么处理呢?

一 运行环境

开发工具:IDEA

后端:Springboot+JPA

前端:thymeleaf+semantic UI

二 代码实现

springboot中已经内嵌了上传图片的依赖包,因此不需要再添加额外依赖。

1 前端页面

<form id="blog-form" action="#" th:object="${blog}" th:action="@{/admin/blogs}" method="post" enctype="multipart/form-data" class="ui form">

              <!--该部分内容省略,以下为重点--> 

               <div class="required field">
                    <div class="ui left labeled input">
                        <label class="ui teal basic label">首图</label>
                        <img src="" th:src="@{*{firstPicture}}" alt="" style="width: 500px !important;">
<!--                        不能给input type="file"文件赋值-->
                        <input type="file" name="picture">
                       <!--<input type="text" name="firstPicture" th:value="*{firstPicture}" placeholder="首图引用地址">-->
                    </div>
                </div>

                <!--该部分内容省略,以上为重点--> 

                <div class="ui right aligned container">
                    <button type="button" class="ui button" onclick="window.history.go(-1)">返回</button>
                    <button type="button" id="save-btn" class="ui secondary button">保存</button>
                    <button type="button" id="publish-btn" class="ui teal button">发布</button>
                </div>
            </form>

注意:enctype的值为multipart/form-data

2 创建上传图片类——UploadImageUtils

package com.hdq.blog_3.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadImageUtils {

//    文件上传
    public static String upload(MultipartFile file){
        if(file.isEmpty()){
            return "";
        }
        String fileName = file.getOriginalFilename();//获取文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//获取文件后缀名
       //重命名文件
        fileName = UUID.randomUUID().toString().replaceAll("-","") + suffixName;
//        windows下
//        String filePath="E:/picture/";
        //centos下
        String filePath="/opt/findBugWeb/picture/";
        File dest = new File(filePath+fileName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try{
            file.transferTo(dest);
        }catch (IOException e){
            e.printStackTrace();
        }
        return filePath.substring(filePath.indexOf("/"))+fileName;
    }
}

3 配置图片访问路径的类——SourceMapperConfig

该类可以指定图片的访问路径。

package com.hdq.blog_3.sourceMapper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//配置文件访问路径
@Configuration
public class SourceMapperConfig implements WebMvcConfigurer {

//    private String fileSavePath = "E:/picture/";
      String fileSavePath="/opt/findBugWeb/picture/";
    /**
     * 配置资源映射
     * 意思是:如果访问的资源路径是以“/images/”开头的,
     * 就给我映射到本机的“E:/images/”这个文件夹内,去找你要的资源
     * 注意:E:/images/ 后面的 “/”一定要带上
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/opt/findBugWeb/picture/**").addResourceLocations("file:"+fileSavePath);
    }
}

4 创建Controller类——BlogController

package com.hdq.blog_3.web.admin;

import com.hdq.blog_3.po.Blog;
import com.hdq.blog_3.po.User;
import com.hdq.blog_3.service.BlogService;
import com.hdq.blog_3.service.TagService;
import com.hdq.blog_3.service.TypeService;
import com.hdq.blog_3.util.UploadImageUtils;
import com.hdq.blog_3.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class BlogController {

    private static final String INPUT="admin/blogs-input";
    private static final String LIST="admin/blogs";
    private static final String REDIRECT_LIST="redirect:/admin/blogs";

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    private void setTypeAndTag(Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("tags",tagService.listTag());
    }

    //新增 or 修改
    @PostMapping("/blogs")
    public String post(@RequestParam("picture") MultipartFile picture, Blog blog, RedirectAttributes attributes, HttpSession session){
        blog.setUser((User) session.getAttribute("user"));
        blog.setType(typeService.getType(blog.getType().getId()));
        blog.setTags(tagService.listTag(blog.getTagIds()));
        //1.修改:picture为空,则不改变FirstPicture,否则改变FirstPicture。
        //2.新增:直接添加图片文件
        Blog b;
        if(blog.getId() == null){
            blog.setFirstPicture(UploadImageUtils.upload(picture));//重点
            b=blogService.saveBlog(blog);
        }else{
//            isEmpty()与null的区别:前者表示内容是否为空,后者表示对象是否实例化,在这里前端发送请求到后端时,就实例化了picture对象
            if(picture.isEmpty()){

           blog.setFirstPicture(blogService.getBlog(blog.getId()).getFirstPicture());//重点
            }else {
                blog.setFirstPicture(UploadImageUtils.upload(picture));//重点
            }
            b=blogService.updateBlog(blog.getId(),blog);
        }
        if(b == null){
            attributes.addFlashAttribute("message","操作失败!");
        }else{
            attributes.addFlashAttribute("message","操作成功!");
        }
        return REDIRECT_LIST;
    }
}

注意:以上部分不重要的代码已删掉,只留下重要部分。

三 运行结果展示

1 初始页面

2 新增成功页面

a.添加图片

b.新增成功

3 修改成功页面

到此这篇关于关于Springboot在新增和修改下上传图片并显示的问题的文章就介绍到这了,更多相关springboot新增修改上传图片内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot上传图片文件步骤详解

    步骤一:基于前面springboot入门小demo 基于的springboot入门小demo,已包含了前面文章的知识点(比如:热部署.全局异常处理器). 步骤二:创建uploadPage.jsp上传页面 在jsp目录下新建uploadPage.jsp,需要几点: 1. method="post" 是必须的 2. enctype="multipart/form-data" 是必须的,表示提交二进制文件 3. name="file" 是必须的,和后续

  • springboot实现后台上传图片(工具类)

    本文实例为大家分享了springboot实现后台上传图片的具体代码,供大家参考,具体内容如下 1.先配置启动类 继承WebMvcConfigurer 重写方法 @SpringBootApplication //@MapperScan("com.example.demo.Mapper") public class DemoApplication implements WebMvcConfigurer { public static void main(String[] args) { S

  • SpringBoot如何上传图片

    1.前端准备 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&

  • SpringBoot上传图片的示例

    说明:通常项目中,如果图片比较多的话,都会把图片放在专门的服务器上,而不会直接把图片放在业务代码所在的服务器上.下面的例子只是为了学习基本流程,所以放在了本地. 1.单张图片上传 1.1.前端用表单提交 前端代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </he

  • 详解SpringBoot上传图片到阿里云的OSS对象存储中

    启动idea创建一个SpringBoot项目 将上面的步骤完成之后,点击下一步创建项目 创建完成之后修改pom.xml文件,添加阿里云oss依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional&g

  • 解决springboot上传图片后无法立即访问需重启的问题

    1)创建配置类实现 WebMvcConfigurer 2)重写addResourceHandlers 方法进行设置 说明:/images/** images 为相对路径 即resources/static 目录下的静态资源 images为存放图片的目录 file:D:\code\java\work\transpond-friends-circle\src\main\resources\static\images\ 该路径为绝对路径 即你在电脑打开该图片文件夹的路径 到此这篇关于解决springb

  • 关于Springboot在新增和修改下上传图片并显示的问题

    解决的问题: 本篇文章除了解决上传图片并显示的问题,还有就是在新增和修改下的图片上传如何处理.在这里新增和修改的页面是同一页面,修改的时候,将会把值带过去,但是由于类型为file的input标签是不能给其赋值的,那么若不改变原来图片,但是input标签中又没有值,这时怎么处理呢? 一 运行环境 开发工具:IDEA 后端:Springboot+JPA 前端:thymeleaf+semantic UI 二 代码实现 springboot中已经内嵌了上传图片的依赖包,因此不需要再添加额外依赖. 1 前

  • KindEditor在php环境下上传图片功能集成的方法示例

    KindEditor 是一套开源的在线HTML编辑器, 后台可与 Java..NET.PHP.ASP 等程序集成.为实现图文混排的编辑效果,我们通常都会用到编辑器的图片上传功能,本文会简单讲一下KinEditor的基本使用,主要说明如何在php环境下,集成编辑器的图片上传功能! KindEditor 官方下载:http://kindeditor.net/down.php KindEditor 编辑器的基本使用:http://kindeditor.net/docs/usage.html KindE

  • 如何基于Springboot完成新增员工功能并设置全局异常处理器

    目录 1. 新增员工 1.1 需求分析 1.2 数据模型 1.3 程序执行流程 1.4 代码实现 2 全局异常处理 2.1 新增员工存在的问题 2.2 全局异常处理思路 2.3 全局异常处理器 2.4 全局异常处理器代码实现 2.5 测试 总结 1. 新增员工 1.1 需求分析 后台系统中可以管理员工信息,通过新增员工来添加后台系统用户.点击[添加员工]按钮跳转到新增页面,如下 当填写完表单信息, 点击"保存"按钮后, 会提交该表单的数据到服务端, 在服务端中需要接受数据, 然后将数据

  • Vue.set()动态的新增与修改数据,触发视图更新的方法

    参数: target:要更改的数据源(可以是对象或者数组) key:要更改的具体数据(可以是字符串和数字) value :重新赋的值 用法:向响应式对象中添加一个属性,并确保这个新属性同样是响应式的,且触发视图更新. 例: data:{ namelist:[ {message:"叶落森",id:"1"}, {message:"姜艳霞",id:"2"}, {message:"姜小帅",id:"3&q

  • Springboot 项目读取Resources目录下的文件(推荐)

    需求描述:企业开发过程中,经常需要将一些静态文本数据放到Resources目录下,项目启动时或者程序运行中,需要读取这些文件. 读取Resources目录下文件的方法 /** * @Description: 读取resources 目录下的文件 * @Author: ljj * @CreateDate: 2020/11/3 17:20 * @UpdateUser: * @UpdateDate: * @UpdateReakem * @param filePath * @Return: java.l

  • mybatis-plus  mapper中foreach循环操作代码详解(新增或修改)

    .循环添加 接口处: 分别是 void 无返回类型 :有的话是(resultType)返回类型,参数类型(parameterType) list , 如: 在mapper文件中分别对应ID,参数类型和返回类型. 循环处理,如下: <insert id="insertPack" parameterType="java.util.List"> insert into t_ev_bu_pack ( PACK_CODE, BIN, PACK_PROD_TIME,

  • vue+elementui 实现新增和修改共用一个弹框的完整代码

    element-ui是由饿了么前端团队推出的一套为开发者.设计师和产品经理准备的基于Vue.js 2.0的桌面组件库,而手机端有对应框架是 Mint UI .整个ui风格简约,很实用,同时也极大的提高了开发者的效率,是一个非常受欢迎的组件库. 一.新增 1.新增按钮 2.新增事件 在methods中,用来打开弹窗, dialogVisible在data中定义使用有true或false来控制显示弹框 **3.新增确定,弹框确定事件 ,新增和修改共用一个确定事件,使用id区别 **3.新增事件 调新

  • SpringBoot中的Condition包下常用条件依赖注解案例介绍

    目录 一.@ConditionalOnClass() Spring中存在指定class对象时,注入指定配置 1.首先引入pom依赖 2.实体类测试对象 3.定义@ConditionalOnClass()配置类 4.启动类测试 二.注入指定配置 1.首先引入pom依赖 2.实体类测试对象 3.定义@ConditionalOnMissingClass()配置类 4.启动类测试 三.加载指定配置 1.首先引入pom依赖 2.实体类测试对象 2.1 引入条件判断实体类 3.定义@ConditionalO

  • SpringBoot深入分析讲解监听器模式下

    我们来以应用启动事件:ApplicationStartingEvent为例来进行说明: 以启动类的SpringApplication.run方法为入口,跟进SpringApplication的两个同名方法后,我们会看到主要的run方法,方法比较长,在这里只贴出与监听器密切相关的关键的部分: SpringApplicationRunListeners listeners = getRunListeners(args); listeners.starting(); 我们跟进这个starting方法,

  • PHP上传图片类显示缩略图功能

    有缩略图功能 但是 感觉不全面,而且有点问题,继续学习,将来以后修改下 <form action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" method="post" ><input type="text" name="name" /><input type="file&q

随机推荐