Image File Handling

2024. 2. 3. 20:56Spring Boot

import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Base64;


@Controller
@RequestMapping("/image")
public class imageController {
    
    @Autowired
    private imageService service;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
        if(service.saveImage(file))
            return ResponseEntity.ok("Image uploaded successfully");
        return ResponseEntity.ok("Image uploaded failed");
    }
    @GetMapping("/list")
    public String listImage(Model model) {
        model.addAttribute("list", service.imageList());
        return "file/image_list";
    }
    
    @GetMapping("/show/{id}")
    public String showImage(@PathVariable Long id, Model model) {
        
        image tmp = service.getImage(id);
        String base64Image = Base64.getEncoder().encodeToString(tmp.getData());
        model.addAttribute("image", base64Image);
        return "file/display";
    }

    @GetMapping("/api/{id}")
    public ResponseEntity<byte[]> imageApi(@PathVariable Long id) {
        image tmp = service.getImage(id);
        byte[] imagebyte = tmp.getData();
        return new ResponseEntity<byte[]>(imagebyte, null, HttpStatus.SC_OK);
    }
    
    @GetMapping("/show/api/{id}")
    public String show_image_api(@PathVariable Long id, Model model) {
        model.addAttribute("id", id);
        return "file/display_api";
    }

    @GetMapping("/test")
    public String uploadPage() {
        return "file/upload";
    }
}

 

 

이미지 파일은 MultipartFile이라는 class로 받아 올 수 있고

<form action="/image/upload" enctype="multipart/form-data" method = "POST">
        <input type = "hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
        <input name="file" type="file">
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>

이는 enctype을 "multipart/form-data"로 하면 form으로 보낼 수 있다

 

 

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.util.*;

@Service
public class imageService {
    
    String[] types = {"jpg", "jpeg", "png", "gif"};

    @Autowired
    private imageRepository repo;

    public List<Long> imageList() {
        return repo.findAllId();
    }
    public boolean saveImage(MultipartFile file) {
        if(typeCheck(file.getOriginalFilename())) {
            image image = new image();
            image.setName(file.getOriginalFilename());
        try {
            image.setData(file.getBytes());
            repo.save(image);
            return true;
        } catch(Exception e) {
            return false;
        }}
        return false;
    }
    public boolean deleteImage(Long id) {
        try {
            repo.deleteById(id);
        }catch (Exception e) {
            return false;
        }
        return true;
    }
    public image getImage(Long id) {
        return repo.findById(id).get();
    }

    boolean typeCheck(String name) {
        String myType = name.substring(name.lastIndexOf(".")+1);
        for(String type : types) {
            if(myType.equals(type))
                return true;
        }
        System.out.printf("%s\n", myType);
        return false;
    }
}

 

받은 MultpartFile 객체는 getBytes()를 이용해 byte 배열을 얻어 이용 할 수 있다

 

 

byte[]를 HTML에 이미지로 출력하는 방법은

이미지를 출력을 위해 byte[]를 return하는 API를 만들거나

타임리프를 이용하면 된다.

 

타임리프를 이용하는 방법은

base64로 인코딩하는 방식인데

@GetMapping("/show/{id}")
    public String showImage(@PathVariable Long id, Model model) {
        
        image tmp = service.getImage(id);
        String base64Image = Base64.getEncoder().encodeToString(tmp.getData());
        model.addAttribute("image", base64Image);
        return "file/display";
    }

 

 

html에서의 타임리프문은

<img  th:src="@{'data:image/jpeg;base64,'+${image}}" />

 

 

 

 

 

 

 

byte[]를 retrun하는 API를 이용하는 방법은

 

    @GetMapping("/api/{id}")
    public ResponseEntity<byte[]> imageApi(@PathVariable Long id) {
        image tmp = service.getImage(id);
        byte[] imagebyte = tmp.getData();
        return new ResponseEntity<byte[]>(imagebyte, null, HttpStatus.SC_OK);
    }
    
    @GetMapping("/show/api/{id}")
    public String show_image_api(@PathVariable Long id, Model model) {
        model.addAttribute("id", id);
        return "file/display_api";
    }

 

<img th:src = "@{https://localhost:5000/image/api/{id}(id = ${id})}">

'Spring Boot' 카테고리의 다른 글

Redis Pub/Sub  (0) 2024.02.19
Elasticsearch  (0) 2024.02.13
Mulit Database by MySQL  (0) 2024.02.03
Redis  (0) 2024.01.28
RestController  (0) 2024.01.28