개발정리

[BUG] 415 (Unsupported Media) error 본문

개발/중거거래사이트 클론

[BUG] 415 (Unsupported Media) error

coffee. 2024. 2. 3. 21:33
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.Service.AuthService;
import com.example.demo.entity.dto.MemberDTO;

@CrossOrigin
@RestController
@RequestMapping("/auth")
public class AuthController {
	
	@Autowired
	private AuthService authService;
	
	@PostMapping("/signup")
	public ResponseEntity<?> signup(@RequestPart(value = "memberDTO") MemberDTO memberDTO,
			@RequestPart(value = "profile") MultipartFile file) throws IOException {
		HashMap<String,Object> hm=new HashMap<>();
		UUID uuid=UUID.randomUUID();
		file.transferTo(Paths.get("src/main/resources/static/images/"+uuid.toString()+"_"+file.getOriginalFilename()));
	
		memberDTO.setProfile(uuid.toString()+"_"+file.getOriginalFilename());
				
		if(authService.signup(memberDTO)) {
			System.out.println("회원가입 성공!");
			hm.put("register_stat",true);
		}
		else {
			System.out.println("회원가입 실패!");
			hm.put("register_stat",false);
		}
		return ResponseEntity.ok(hm);
	}
	
	@PostMapping("/signin")
	public ResponseEntity<?> signin(@RequestBody MemberDTO memberDTO) {
		
		String token = authService.signin(memberDTO);
		
		HashMap<String,String> hm=new HashMap<>();
		hm.put("token",token);
		if(token==null) {	
			return ResponseEntity.badRequest().body(hm);
		}
		else {
			return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE,new HttpCookie("token",token).toString())
					.body(hm);
		}
		
	}
	
	
}

 

 

<template>
    <div class="container">
        <div class="imageDiv"   v-on:click="clickDiv">
            <img src="" id="preview"/>
            <input type="file" id="image" v-on:change="previewChange" style="visibility: hidden;"/>
        </div>
        <input type="text" placeholder="아이디" v-bind="userId"/>
        <input type="password"  placeholder="패스워드" v-bind="password"/>
        <input type="button" value="회원가입" v-on:click="signup" />
    </div>
</template>


<script>
import axios from 'axios';
export default{
    data(){
        return{
            userId:"",
            password:"",
            profile:""
        };
    },
    methods:{
        clickDiv:function(){
            const image=document.getElementById('image');
            image.click();
        },
        previewChange:function(){
            const preview=document.getElementById('preview');
            const image=document.getElementById('image');
            const reader=new FileReader();
            if(image.files[0] ==null){
                return;
            }

            reader.onloadend=()=>{
                preview.src=reader.result;
            }

            console.log(image.files[0]);
            this.$data.profile=image.files[0];
            reader.readAsDataURL(image.files[0]);

        },
        signup:function(){
            const formData =new FormData();
            formData.append('profile',this.$data.profile,{
                type:"image/jpeg"
            });
            formData.append('memberDTO',JSON.stringify({
                userId:this.$data.userId,
                password:this.$data.password
            }));

            axios.post('http://localhost:8080/auth/signup',formData,{
                headers:{
                    "Content-Type":"multipart/form-data",
                    'Accept':'application/json'
                }
            })
                .then(response =>{
                    console.log(response);
                })
        }


    }
}

</script>


<style scoped>
.container{
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    height: 400px;
}
input{
    box-sizing: content-box;
    width: 200px;
    padding: 0;
}

.imageDiv{
    border: 1px solid black;
    border-radius: 50%;
    width: 100px;
    height: 100px;
    overflow: hidden;
}

.imageDiv>img{
    width: 100%;
    height: 100%;
}
</style>

vue.js 에서 axios로 파일과 json을 보내는데 415 (Unsupported Media) error 발생

 

24/02/04 해결

자바스크립트에서 JSON을 전송할 때  new Blob을 사용하여 전송 해야합니다.

 

signup:function(){
            const formData =new FormData();
            const request = {
                userId:this.$data.userId,
                password:this.$data.password
            }

            formData.append('profile',this.$data.profile);
            formData.append('memberDTO',new Blob([JSON.stringify(request)],{type:'application/json'}));
            console.log(this.$data.profile);
            axios.post('http://localhost:8080/auth/signup',formData)
                .then(response =>{
                    console.log(response);
                })
        }