springboot:文件上传,图片上传,后显示图片。存入数据库

springboot:文件上传,图片上传,后显示图片。存入数据库

1.常见核心配置MyWebAppConfigurer

package com.gym.util;

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

/**
 * @author ymgu
 * @version 1.0
 * @date 2022/1/24 15:38
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/temp-rainy/**").addResourceLocations("file:D:/temp-rainy/");
    }
}

2.控制类

/**
     * 文件上传
     * **/
    @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 "activity/test";
    }

3.前端

<div class="login-center">
<form th:action="@{/fileUpload}" method="post" enctype="multipart/form-data">
<label>上传图片label>
<input type="file" name="file"/>
<input type="submit" value="上传"/>
form>
 <p>图片:p>
<img th:src="${filename }"/>
 div>

springboot:文件上传,图片上传,后显示图片。存入数据库_第1张图片

你可能感兴趣的:(java,spring,boot,数据库,java)