天天看點

【Vue】參數傳遞:如何同時傳遞 DTO 和 file 檔案axios 的處理SpringBoot Controller 類配合使用效果圖

日常開發時,如果遇到較為複雜的 DTO 對象的參數傳遞時,通常前端使用的請求頭為:

application/json

(JSON 格式的資料);而後端可以使用

@RequestBody

接收一個 DTO 對象。但當需要在一個界面上同時傳遞 DTO 和附件檔案時,這種方式就不行了。因為傳遞檔案時請求頭必須為:

multipart/form-data

,而後端就無法使用

@RequestBody

注解了。

我準備了如下格式的資料:

{
	name: "名稱",
	vo: {
		name: "名稱",
		remark: "備注"
	},
	voList: [
		{
			name: "名稱1",
			remark: "備注1"
		},
		{
			name: "名稱2",
			remark: "備注2"
		}
	]
}
           

上面的資料如果和檔案同時傳遞,需要使用

multipart/form-data

請求頭傳遞,并且得使用

FormData

append

方法組裝為下面的格式(下面内容是在 Chrome 的控制台中看到的格式):

name: 名稱
vo.name: 名稱
vo.remark: 備注
voList[0].name: 名稱1
voList[0].remark: 備注1
voList[1].name: 名稱2,
voList[1].remark: 備注2
           

axios 的處理

axios 的 create 方法中有一個

transformRequest

的屬性,可以做參數請求前的處理:

import Axios from 'axios'

Axios.create({
    baseURL: '/api',
    headers: {
    	// 預設使用這個請求頭
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    transformRequest: [
        function (data: any, headers: any): any {
            if (headers[ 'Content-Type' ] === 'multipart/form-data') {
                // 這裡需要處理資料
                if (data instanceof FormData) {
                    // FormData 的不需要處理
                    return data;
                } else {
                    // 将file對象之外的處理為 key=value的形式
                    const form = new FormData()
                    for (let key in data) {
                        if (data.hasOwnProperty(key)) {
                            handleValue(form, key, data);
                        }
                    }
                    return form
                }
            } else {
                return Qs.stringify(data, {
                    arrayFormat: 'comma'
                })
            }
        }
    ]
})

function handleValue(form: any, key: string | number, data: any, formKey?: string | number): void {
    let obj = data[key]
    if (obj === undefined) {
        return
    }
    if (typeof obj === 'object') {
        if (obj instanceof File) {
            // 如果是檔案的話直接加到form中
            formKey = formKey ? formKey : key
            form.append(formKey, obj)
        } else if (obj.length !== undefined && obj.length > 0) {
            // 是一個數組
            // 繼續循環處理for
            let length = obj.length
            for (let i = 0; i < length; i++) {
                handleValue(form, i, obj, key)
            }
        } else {
            // 是一個對象了
            formKey = formKey ? formKey + '[' + key + '].' : key + '.'
            for (let k in obj) {
                if (obj.hasOwnProperty(k)) {
                    form.append(formKey + k, obj[k])
                }
            }
        }
    } else {
        form.append(key, obj);
    }
}
           

SpringBoot Controller 類

這裡就沒有需要注意的地方了:

@PostMapping("upload_test")
public String test(DTO dto, MultipartFile[] files) {
	// 其他處理
	return "success";
}
           

配合使用

如何上面的前後端配合使用的話,前端調用 axios 的 post 方法時,按照如下使用即可:

<template>
    <div class="home">
        <input type="file" id="file"/>
        <br/><br/>
        <input type="button" value="上傳" @click="click"/>
    </div>
</template>

<script lang="ts">
    import {defineComponent} from 'vue'
    import http from '../api/http'

    const data = {
        vo: {
            name: '名稱',
            remark: '備注'
        },
        voList: [
            {
                name: '名稱1',
                remark: '備注1'
            },
            {
                name: '名稱2',
                remark: '備注2'
            }
        ]
    }

    export default defineComponent({
        name: 'HomeView',
        setup() {
            const click = () => {
                Object.assign(data, {
                    files: [
                        (document.getElementById('file') as HTMLInputElement)?.value,
                        (document.getElementById('file') as HTMLInputElement)?.value
                    ]
                })
                // ******************** 重點關注這裡  ********************
                http.post('/test/upload_test', data, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(res => alert(res))
            }

            return {
                click
            }
        }
    });
</script>
           

效果圖

放一張 gif 的效果圖:

【Vue】參數傳遞:如何同時傳遞 DTO 和 file 檔案axios 的處理SpringBoot Controller 類配合使用效果圖