Spring Boot 이미지 업로드 및 리 턴 기능 구현

일반 형식
1 항목 구조

2 프로필 및 환경 설정
(1)프로필

#      WEB     
server.port=8080
# spring         
spring.resources.static-locations=classpath:/static/
#   template  html        
spring.thymeleaf.prefix.classpath=classpath:/templates/
#       
spring.thymeleaf.cache=false
#       
spring.thymeleaf.suffix=.html
#       
spring.thymeleaf.encoding=UTF-8
#       
file.upload.path=G://images/     #   #
#          
file.upload.path.relative=/images/**      #   #
#       
spring.servlet.multipart.max-file-size=5MB
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lxFge7I3-1625452749715)(C:\Users\17122\AppData\Roaming\Typora\typora-user-images\image-20201106192605478.png)]
3 코드
(1)pom.xml

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>
(2)index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="../upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" accept="image/*">
    <br>
    <input type="text" value="">
    <input type="submit" value="  " class="btn btn-success">
</form>
[[${filename}]]
<br>
<img th:src="@{${filename}}" alt="  ">
</body>
</html>
(3)TestController.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class TestController {

    /**
     *     
     */
    @Value("${file.upload.path}")
    private String filePath;

    //       
    @RequestMapping("test")
    public String test() {
        return "Page";
    }

    //     
    @RequestMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) {
        //        
        String filename = file.getOriginalFilename();
        //           
        String path = filePath + "rotPhoto/";
        //     
        File filepath = new File(path, filename);
        //         ,          
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        try {
            //     
            file.transferTo(new File(path + File.separator + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //  src     html  
        model.addAttribute("filename", "/images/rotPhoto/" + filename);
        return "index";
    }
}
(4)MyWebAppConfigurer

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 MyWebAppConfigurer implements WebMvcConfigurer {

    /**
     *     
     */
    @Value("${file.upload.path}")
    private String filePath;
    /**
     *       
     */
    @Value("${file.upload.path.relative}")
    private String fileRelativePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(fileRelativePath).
                addResourceLocations("file:/" + filePath);
    }
}
4 테스트
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HU02Yilv-1625452749717)(C:\Users\17122\AppData\Roaming\Typora\typora-user-images\image-20201106200633411.png)]
2.비동기 작업 증가
1 전단 ajax

<div class="modal-body">
     <form method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="img">
        <input type="button" value="  " class="btn btn-outline-primary" onclick="uploadFile()"
                               style="width: 30%;">
     </form>
</div>
<script>
//    
function uploadFile() {
    //formData         ,  key/value      ,key    ,  key      value
    var myform = new FormData();
    //       append()       
    myform.append('file', $("#img")[0].files[0]);
    //     
    var file = $("#img")[0].files[0];
    if (file == null) {
        alert("     ");
        return false;
    } else {
        $.ajax({
            url: "/user/upLoad",
            type: "POST",
            data: myform,
            async: false,
            contentType: false,
            processData: false,
            success: function (result) {
                console.log(result);
                alert("    !");
                $("#div_show_img").html("<img id='input_img' src='" + result + "'>");
                $("#imgPath").attr("value", result);
                $("#div_upload").removeClass("show");
            },
            error: function (data) {
                alert("    ");
            }
        });
    }
}
</script>
2 백 엔 드 컨트롤 러

@ResponseBody
@RequestMapping("/upLoad")
public String upLoadImage(@RequestParam("file") MultipartFile file) {
    //        
    String filename = file.getOriginalFilename();
    String suffixName = filename.substring(filename.lastIndexOf("."));
    //           
    String path = filePath + "images/";
    //        
    String newImgName = UUID.randomUUID().toString() + suffixName;
    //     
    File filepath = new File(path, newImgName);
    //         ,          
    if (!filepath.getParentFile().exists()) {
        filepath.getParentFile().mkdirs();
    }
    try {
        //     
        file.transferTo(new File(path + File.separator + newImgName));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "/images/images/" + newImgName;
}
여기 서 Spring Boot 가 이미지 업로드 와 리 플레이 기능 을 실현 하 는 것 에 관 한 글 은 여기까지 소개 되 었 습 니 다.더 많은 Spring Boot 가 이미지 리 플레이 내용 을 올 리 려 면 예전 의 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기