공개/Spring

[SpringBoot] FormData로 받은 이미지 로컬에 저장하기

잔망짱구 2023. 5. 21. 20:02
728x90
반응형

2023.02.17 - [JavaScript/Vue] - [Vue.js] Axios를 이용해 FormData 이미지 보내기

 

[Vue.js] Axios를 이용해 FormData 이미지 보내기

현재 vue.js 와 springboot 를 통신 중인데, 이미지 업로드를 시도하고 있다. form으로 전체를 감싸는 것 말고, 폼 데이터로 보내는 법을 기록해보겠다! vue.js 사진: @change 를 활용해 input을 했을 때 setPhot

wonny.kim

 

Springboot

@PostMapping(value = "/image", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public @ResponseBody String addPhoto(@RequestParam("image") MultipartFile img) {

        UUID uuid = UUID.randomUUID();
        String imageFileName = uuid+"_"+img.getOriginalFilename();

        String path = "원하는 폴더";
        Path imagePath = Paths.get(path+imageFileName);

        try{
            Files.write(imagePath, img.getBytes());
        }
        catch(Exception e){
            System.out.println(e);
        }
        System.out.println(img.getOriginalFilename());

        return imageFileName;
}

vue

<template>
    <div class="menu">
        <input type="file" @change="setImage()" accept="image/*" id="image">
    </div>
</template>
<script>
import axios from 'axios';
export default {
    data(){
        return{
            image: null
        }
    },
    methods: {
        setImage(){
            let frm = new FormData();
            let imageFile = document.getElementById("image");
            frm.append("image", imageFile.files[0]);

            axios.post("/api/users/image", frm, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then(()=>{
                console.log("전송 성공");
            })
            .catch((e)=> {
                console.log(e);
            })
        },
 }
}
728x90
반응형