目錄
formData是甚麼
formData object是一種物件,裡面裝了key和value組成的資料。key為欄位名,value則為欄位值
不同格式
的資料可以透過一個request
發送,常被用於傳資料給server
,且比
起把檔案轉為base64
再送出去來得小
建立、使用formData
HTML有form tag時
<template>
<div>
<form ref="form" class="flex flex-col mb-3">
<input type="text" name="text1" value="foo" class="mb-2">
<input ref="file" type="file" name="file">
</form>
<button class="button" @click="generate">generate formData</button>
<output ref="output"></output>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
name: 'Foo',
data(){
return{
}
},
methods:{
generate():void{
const output = this.$refs.output as HTMLOutputElement;
// 把form丟入formData constructor,formData就會根據name、value屬性被構成
// An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
const formData = new FormData(this.$refs.form as HTMLFormElement);
output.textContent = '';
for (const [key, value] of formData) { // formData可以直接被迭代,不必先透過formData.entries()取得keys
output.textContent += `${key}: ${value}\n`;
}
}
}
})
</script>
HTML無form tag時
<template>
<div>
<input ref="text1" type="text" name="text1" value="foo" class="mb-2">
<input ref="file" type="file" name="file">
<button class="button" @click="generate">generate formData</button>
<output ref="output"></output>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
name: 'Foo',
data(){
return{
}
},
methods:{
generate():void{
const output = this.$refs.output as HTMLOutputElement;
const formData = new FormData();
// 使用append()可以自行插入值到formData,set()也可以插入值。兩者差在如果key已經存在,set會把舊值洗掉,append則否
// 若要移除則用delete()
formData.append('text1', (this.$refs.text1 as HTMLInputElement).value);
formData.append('file', ((this.$refs.file as HTMLInputElement).files as FileList)[0]);
output.textContent = '';
for (const [key, value] of formData) {
output.textContent += `${key}: ${value}\n`;
}
}
}
})
</script>