programing

Axios를 사용하여 이미지를 서버에 업로드하려면 어떻게 해야 합니까?

prostudy 2022. 5. 30. 22:02
반응형

Axios를 사용하여 이미지를 서버에 업로드하려면 어떻게 해야 합니까?

이미지와 함께 폼을 보내려고 합니다.주의: 이미지를 데이터베이스에 저장하는 것이 아니라 서버에서 작성한 폴더에 저장하고 이미지에 대한 링크를 데이터베이스에 추가합니다.

서버 측에서는 이 조작 방법을 알고 있습니다만, 폰트 엔드에서는 조작 방법을 모릅니다.즉, Axios를 사용하여 어떻게 이미지를 서버로 보낼 수 있습니까?

<template>
    <input type="text" class="form-control" id="specdesc" v-model="product.specdesc" name="specdesc" placeholder="Enter your name">
    <input type="file"  name="image" id="image"  accept="image/*" >
    <button type="submit" class="btn btn-sm btn-primary"@click.prevent="Submit()"> Submit</button>
</template>

<script>
export default {
   name: 'Addproduct',
   data(){
        return{
            image: '',
            product:{
                specdesc:'',
            },
        }
    },
    methods:{ 
      Submit(){
        var _this=this

        //  console.log(this.image)
        console.log(this.selectedCategory.category_name)
        var product = {
            specification:this.product.specdesc,
            imagename:this.image
        }
          
        this.$http.post('http://localhost:3000/api/companyproducts',product) 
        .then(function (response) {
            console.log(response.data);
        })
        .catch(function (error) {
            console.log("error.response");
        });
        }
    },
}
</script>

그럼 어떻게 하면 이미지 및 입력명을 악시스를 사용하여 업로드 할 수 있을까요?게다가 같은 방법을 사용하고 싶다.var product송신할 수 있습니다.

표준(대부분) 접근법은 로직을 두 개로 분할하는 것입니다.product먼저 사진을 서버에 업로드하고 경로를 반환해야 합니다.

유사 예:

컴포넌트 데이터

    {
      imagePath: '',
      productSpect: ''
    }
``

``html

<input type="text" v-model="productSpect" />
<input type="file" @change="uploadImage" name="image" id="image"  accept="image/*" >
<button type="submit" @click.prevent="submit"> Submit</button>`

``

**uploadImage method**

    uploadImage (e) {
      let img = e.target.files[0]
      let fd= new FormData()
    
      fd.append('image', img)
    
      axios.post('/upload-image', fd)
        .then(resp => {
           this.imagePath = resp.data.path
        })
    }


**submit method**

    submit () {
      let data = {
        imagePath: this.imagePath,
        productSpect: this.productSpect
      }
    
      axios.post('/path/to/save', data)
    }



**edited method to handle just only 1 image on the server**

Change the input `@change` to just save the img on a property under data():

    <input type="file" @change="image = e.target.file[0]" name="image" id="image"  accept="image/*" >

    submit() {
      let fd= new FormData()
    
      fd.append('image', this.image)
    
      axios.post('/upload-image', fd)
        .then(resp => {
           this.imagePath = resp.data.path
    
           let data = {
             imagePath: this.imagePath,
             productSpect: this.productSpect
           }
        
           axios.post('/path/to/save', data)
        })
    }

이 질문에는 Vue에 대한 구체적인 내용은 없습니다.POST 요구를 악시오와 함께 송신하기 위해서는 html 폼의 formData를 데이터 인수로 Axios에 전달하는 것이 가장 간단합니다.Vue에서 이 작업을 수행하려면 폼 태그를 참조하고 폼에서 폼 데이터를 생성하십시오.

<form ref="myForm">

// then in your method...
var myFormData = new FormData(this.$refs.myForm)
axios({
    method: 'post',
    url: 'myurl',
    data: myFormData,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
})

업로드 파일의 경우 vuetify https://vuetifyjs.com/en/components/file-inputs/ 를 사용해 왔습니다.

 <v-file-input
   accept="image/png, image/jpeg, image/bmp"
   placeholder="Pick an avatar"
   prepend-icon="mdi-camera"
   v-model="imageData"
  ></v-file-input>
 <v-btn color="primary" @click="onUpload">Upload</v-btn>

내 vue 방식으로는

onUpload() {      
    let formData = new FormData();
    formData.append('file', this.imageData);
    axios.post(
        "/images/v1/upload"
        ,formData
        ,{headers: {"Content-Type": "multipart/form-data"}}
    )
    .then(response => {
      //...
    })
    .catch(e => {
       //...
    })
}

안부 전합니다!

언급URL : https://stackoverflow.com/questions/49299643/how-can-i-upload-image-to-server-using-axios

반응형