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
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 테스트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 가 이미지 리 플레이 내용 을 올 리 려 면 예전 의 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부 탁 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.