여유상점_0907 : 6) fetchi api post both files and text

오범준·2020년 9월 9일
0

I want to send both files and text through post request

1st trial : Make my own object and add all the texts and files with the ( key : value )

For example

    let Datas = {}
    
    
    // input : type = "text" with class = "input_text"
    let InputTexts = document.querySelectorAll('.input_text')
    InputTexts.forEach((text) => {
        Datas[text.attributes.id.value] = text.value
        //console.log(text.value)
        //console.log(text.attributes.id.value)
    })

    // JUST input : type = "text"
    Datas['Location'] = Location.value
    Datas['SubLocation'] = SubLocation
    Datas['Is_New'] = Is_New
    Datas['Is_Hot'] = Is_Hot

and send it thorought Fetch api with JSON.stringfy

    fetch('http://localhost:3100/admin/projectUpload', {
        method : 'POST',
        // content_type : may need to be ommited
        headers: {'Content-Type':'application/json'},
        // If you add this, upload won't work
        // headers: {
        //   'Content-Type': 'multipart/form-data',
        // }
        body :  JSON.stringify(Datas)
    })

It is sending the Object Datas to the backend
but since I am ... making 'Datas' object to "string"

the file included in the 'Datas' is not recognized properly as the 'file'
in the backend

So I have to use other method

2nd trial ( Solved ): use FormData with 'Content-type ' removed in fetch api code


    let Data_Form = new FormData()

    // input : type = "text" with class = "input_text"
    let InputTexts = document.querySelectorAll('.input_text')
    InputTexts.forEach((text) => {
        Data_Form.append(text.attributes.id.value, text.value)
        //console.log(text.value)
        //console.log(text.attributes.id.value)
    })
    // JUST input : type = "text"
    Data_Form.append('Location', Location.value)
    Data_Form.append('SubLocation', SubLocation )
    Data_Form.append('Is_New', Is_New )
    Data_Form.append('Is_Hot', Is_Hot )

    // Files_ Images
   Data_Form.append('MainPhoto1', MainPhoto1)
   Data_Form.append('MainPhoto2', MainPhoto2)
   Data_Form.append('MainPhoto3', MainPhoto3)
   Data_Form.append('CreatPhoto', CreatPhoto)

   // Files_ 첨부 파일 등
   Data_Form.append('AddedFile', AddedFile )   

   // TextAreas
   TextAreas.forEach((TextArea) => {
        Data_Form.append(TextArea.attributes.id.value, TextArea.value)
   })

    fetch('http://localhost:3100/admin/projectUpload', {
        method : 'POST',
        // content_type : may need to be ommited
        // If you add this, upload won't work
        // headers: {
        //   'Content-Type': 'multipart/form-data',
        // }
        body : Data_Form
    })
profile
Dream of being "물빵개" ( Go abroad for Dance and Programming)

0개의 댓글