在 Vue 3 中,如果你想將文件(例如上傳的 Excel 文件)以 FormData
格式發送到后端,可以通過以下步驟實現。這種方式通常用于處理文件上傳,因為它可以將文件和其他數據一起發送到服務器。
首先,創建一個 Vue 組件,用于選擇文件并將其封裝到 FormData
中。
示例代碼:
<template>
? <div>?????????<input type="file" class="file-btn hoverPointer" accept=".xls,.xlsx" ????????@change="changeExcel($event)" />
?<div class="button2 primary" @click="clickImport">立即導入</div>
? </div>
</template><script setup lang="ts">
import { ref } from 'vue'
import { apiGetDownloadImportFile, apiPostImportData, apiPostImportDataLogPage } from '@/api/encouragementApi'
import { useAjax } from '@/hooks/common'
let fileValue = ref<any>(null) // 存儲文件
const changeExcel = (e: any) => {
? const files = e.target.files
? if (files.length <= 0) {
? ? return false
? } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
? ? console.log('上傳格式不正確,請上傳xls或者xlsx格式')
? ? return false
? }
? fileValue.value = files[0]
}
// 立即導入
const clickImport = () => {
? const formData = new FormData()
? formData.append('file', fileValue.value)
// 調接口
? useAjax({
? ? apiName: apiPostImportData({
? ? ? encourageTypeId: 1,
? ? ? file: formData
? ? }),
? ? success: (res: any) => {
? ? ? console.log(res)
? ? },
? ? failure: () => {
? ? ? console.log('導入失敗')
? ? }
? })
}
</script>