SpringBoot 实现文件上传,图片上传并显示功能

我先看一下《颈椎病康复指南》再给大家说怎么实现的这两个功能,毕竟只是一个新手,解决这种复杂点的问题(相对而言),还是需要花费大量时间的,这篇文章花了两天的时间才实现的功能,现在就记录一下使用springboot怎么实现文件上传下载的。

我这里使用的是 springboot 2.0.3,不需要导入相关jar包,2.x 的版本已经整合进去了,直接使用即可。

spring官网提供了 springboot 的文件上传下载案例,这是网址:https://spring.io/guides/gs/uploading-files/,使用的是流的输出,对于我这个新手来说,直接不理解,所以略过,通过网上查阅大量资料,终于把问题解决了。下面的案例是 springboot2.x 图片上传与回显。我使用的工具是idea。

1、创建idea默认的springboot项目,我的版本是2.0.3

2、创建一个控制层FileController

package com.rainy.controller;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * 文件上传
 */
@Controller
public class FileController {

    @GetMapping(value = "/file")
    public String file() {
        return "file";
    }

    @PostMapping(value = "/fileUpload")
    public String fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request) {
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://temp-rainy//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = "/temp-rainy/" + fileName;
        model.addAttribute("filename", filename);
        return "file";
    }
}

3、创建MyWebMvcConfigurer,这里是配置资源映射路径,详细点的介绍看这篇文章:https://blog.csdn.net/qq_38762237/article/details/81283241

/**
 * 资源映射路径
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/temp-rainy/**").addResourceLocations("file:D:/temp-rainy/");
    }
}

4、jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    

图片:

注意一点:我是使用jsp引擎来渲染,因为我不会用 Thymeleaf,添加jsp页面,springboot使用jsp页面是需要进行配置jsp整合的,默认的是 Thymeleaf 的页面,简单的就是HTML页面

springboot配置jsp页面的方法:https://blog.csdn.net/qq_38762237/article/details/81283352

SpringBoot 实现文件上传,图片上传并显示功能_第1张图片

如果有什么问题的话,可以告诉我,QQ:3210054449,或者评论留言,这是我的首页:https://blog.csdn.net/qq_38762237,都是我在学习过程中遇到的一些问题做的记录。、

交流

在这里插入图片描述

你可能感兴趣的:(SpringBoot,javaweb,SpringBoot,专栏)