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

 更新时间:2021年04月27日 11:22:22   作者:找找Bug  
这篇文章主要介绍了关于Springboot在新增和修改下上传图片并显示的问题及解决方法,在这里 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新增修改上传图片内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中Map的遍历方法及性能测试

    Java中Map的遍历方法及性能测试

    这篇文章主要介绍了Java中Map的遍历方法及性能测试,本文讲解对HashMap、TreeMap进行对比测试,给出测试代码、测试结果和测试结论,需要的朋友可以参考下
    2015-01-01
  • 详解用java描述矩阵求逆的算法

    详解用java描述矩阵求逆的算法

    这篇文章主要介绍了用java描述矩阵求逆的算法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • mybatis执行批量更新batch update 的方法(oracle,mysql两种)

    mybatis执行批量更新batch update 的方法(oracle,mysql两种)

    这篇文章主要介绍了mybatis执行批量更新batch update 的方法,提供oracle和mysql两种方法,非常不错,需要的朋友参考下
    2017-01-01
  • Mybatis的类型转换接口TypeHandler

    Mybatis的类型转换接口TypeHandler

    这篇文章主要介绍了Mybatis的类型转换接口TypeHandler,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-08-08
  • Springboot解决ajax+自定义headers的跨域请求问题

    Springboot解决ajax+自定义headers的跨域请求问题

    由于浏览器同源策略(同源策略,它是由Netscape提出的一个著名的安全策略,现在所有支持JavaScript 的浏览器都会使用这个策略。接下来通过本文给大家介绍Springboot如何优雅的解决ajax+自定义headers的跨域请求 ,需要的朋友可以参考下
    2019-05-05
  • IDEA 中 30 秒创建一个 Spring Cloud Alibaba 工程

    IDEA 中 30 秒创建一个 Spring Cloud Alibaba 工程

    这篇文章主要介绍了IDEA 中 30 秒生成 Spring Cloud Alibaba 工程,本文通过图文并茂的形式给大家介绍的非常详细对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-04-04
  • Java中jqGrid 学习笔记整理——进阶篇(二)

    Java中jqGrid 学习笔记整理——进阶篇(二)

    这篇文章主要介绍了Java中jqGrid 学习笔记整理——进阶篇(二)的相关资料,需要的朋友可以参考下
    2016-04-04
  • MyBatis-Plus简介和快速入门教程

    MyBatis-Plus简介和快速入门教程

    MyBatis-Plus是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做修改,为简化开发、提高效率而生,本文给大家介绍MyBatis-Plus简介和快速入门教程,需要的朋友参考下吧
    2021-09-09
  • Java中null的意义及其使用时的注意事项说明

    Java中null的意义及其使用时的注意事项说明

    这篇文章主要介绍了Java中null的意义及其使用时的注意事项说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • Dubbo3和Spring Boot整合过程源码解析

    Dubbo3和Spring Boot整合过程源码解析

    Dubbo首先是提供了一个单独的模块来和Spring Boot做整合,利用 Spring Boot自动装配的功能,配置了一堆自动装配的组件,本文介绍Dubbo3和Spring Boot整合过程,需要的朋友一起看看吧
    2023-08-08

最新评论