Vite 上傳照片 使用fileReader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<template>
<el-form
ref="ruleFormRef"
:model="ruleForm"
:rules="rules"
class="add_person_set_form">
<div class="col_4">
<el-form-item class="avatar_input" prop="photo1">
<div class="pic_img" v-show="file!=''">
<img :src="file" />
</div>
<div class="file_discription">
{{fileContent}}
</div>
<label for="imgFile" class="file-upload">
<i class="fa fa-cloud-upload"></i>
上傳照片
<input
class="form-control"
type="file" id="imgFile" accept=".jpg,.jpeg,.png"
@change="fileChangehandler" />
</label>
</el-form-item>
</div>
</el-form>
</template>

<script setup lang="ts">
import { ref,reactive, onMounted,computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()
// 表單
const ruleForm=ref<any>({
photo1: "",//照片})

//檔案路徑
const file =ref<string>('');
//檔案名稱
const fileContent=ref<string>('');
const fileChangehandler =(e:any)=>{
console.log(e.target)
//建立 fileReader 物件
const reader = new FileReader
//readAsDataURL 方法: 開始讀取指定的 Blob,讀取完成後屬性 result 將以 data: URL 格式(base64 編碼)的字串來表示讀入的資料內容。
reader.readAsDataURL(e.target.files[0])
//onload 事件: 於讀取完成時觸發。
reader.onload = () => {
//reader.result 為檔案的內容
file.value = reader.result;
console.log('file.value:', file.value)
fileContent.value=e.target.files[0].name;
}
reader.onerror = (error) => {
console.log('Error:', error)
}
}

=>建立 fileReader 物件
=>readAsDataURL 方法: 開始讀取指定的 Blob,讀取完成後屬性 result 將以 data: URL 格式(base64 編碼)的字串來表示讀入的資料內容。
=>onload 事件: 於讀取完成時觸發。
=>onerror 錯誤訊息
參考資料