关于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新增修改上传图片内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Spring Security登录表单配置示例详解

    Spring Security登录表单配置示例详解

    这篇文章主要介绍了Spring Security登录表单配置,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-06-06
  • hadoop 切片机制分析与应用

    hadoop 切片机制分析与应用

    切片这个词对于做过python开发的同学一定不陌生,但是与hadoop中的切片有所区别,hadoop中的切片是为了优化hadoop的job在处理过程中MapTask阶段的性能达到最优而言
    2022-02-02
  • Java 文件传输助手的实现(单机版)

    Java 文件传输助手的实现(单机版)

    这篇文章主要介绍了Java 文件传输助手的实现(单机版),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • SpringBoot热部署配置过程

    SpringBoot热部署配置过程

    这篇文章主要介绍了SpringBoot热部署配置过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03
  • Java关键字之instanceof详解

    Java关键字之instanceof详解

    instanceof是Java的一个二元操作符,和==,>,<是同一类东东。由于它是由字母组成的,所以也是Java的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回boolean类型的数据
    2021-11-11
  • Java正则表达式判断字符串中是否包含中文示例

    Java正则表达式判断字符串中是否包含中文示例

    之前一个朋友问我,如何判断字符串中是否包含中文,其实解决的方法很简单,但觉着有必要写出给不知道的朋友们以参考,所以下面这篇文章主要介绍了利用Java正则表达式判断字符串中是否包含中文的方法,需要的朋友可以参考。
    2017-03-03
  • java调用微信现金红包接口的心得与体会总结

    java调用微信现金红包接口的心得与体会总结

    这篇文章主要介绍了java调用微信现金红包接口的心得与体会总结,有需要的朋友可以了解一下。
    2016-11-11
  • MyEclipse开发一个webservice接口

    MyEclipse开发一个webservice接口

    这篇文章主要为大家详细介绍了MyEclipse开发一个webservice接口,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-07-07
  • Java中super关键字介绍以及super()的使用

    Java中super关键字介绍以及super()的使用

    这几天看到类在继承时会用到this和super,这里就做了一点总结,下面这篇文章主要给大家介绍了关于Java中super关键字介绍以及super()使用的相关资料,需要的朋友可以参考下
    2022-01-01
  • java实现简单验证码生成

    java实现简单验证码生成

    这篇文章主要介绍了java实现简单验证码生成,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-10-10

最新评论