Vue3 ts實現將assets中的圖片轉為file格式,實現本地圖片選擇上傳功能
- 1、需求描述
- 2、關鍵代碼
- 3、img標簽src使用變量打包后圖片無法展示
1、需求描述
用戶可以選項系統固定的幾個圖標,也可以自定義上傳圖片。系統固定圖標存在 src\assets\images\app 路徑中。
2、關鍵代碼
文件轉換關鍵代碼
const moudles: any = import.meta.glob('@/assets/images/app/*') // 獲取所有默認圖標
// path 格式為 '/src/assets/images/app/*******.png'
const createFileFromImage = async (path: string, name: string) => {moudles[path]().then(async (res: { default: string | URL }) => {// 將文件轉為blob格式const response = await fetch(new URL(res.default, import.meta.url))const arrayBuffer = await response.arrayBuffer()const blob = new Blob([arrayBuffer], { type: 'image/png' })// blob格式轉化為file格式const file = new File([blob], name, { type: 'image/png' })// 依據實際請求需求,還可轉換為formData格式const formData = new FormData()formData.append('file', file)// 你的處理邏輯,我賦值給了a-upload組件的變量coverFileList.value = [{name: randomImgName.value,uid: '-1',originFileObj: file as any}]})
}
給a-upload組件初始化一個隨機系統圖標關鍵代碼
圖片為系統內置的10張圖片
const randomImgName = ref(`default-${getRandomNumber(1, 10)}.png`) // 隨機獲取一張圖片
const randomImgPath = ref(`/src/assets/images/app/${randomImgName.value}`) // 圖片地址
createFileFromImage(randomImgPath.value, randomImgName.value) // 調用文件轉換方法/*** 獲取指定范圍隨機數* @param min 最小值* @param max 最大值*/
const getRandomNumber = (min: number, max: number) => {return Math.floor(Math.random() * (max - min + 1)) + min
}
3、img標簽src使用變量打包后圖片無法展示
問題: img標簽src使用變量打包后會出現圖片無法展示
原因:vite 官方默認的配置,如果資源文件在assets文件夾打包后會把圖片名加上 hash值,但是直接通過 :src="imgSrc"方式引入并不會在打包的時候解析,導致開發環境可以正常引入,打包后卻不能顯示的問題
import.meta.glob():在vue2中支持require導入模塊或文件,但是在vue3不支持require,可以使用import.meta.glob方法來支持批量導入文件
html代碼塊
<img :src="imgUrl[index - 1]" @click="changeDefaultImg(`default-${index}.png`)" />
typescript 代碼塊
const moudles: any = import.meta.glob('@/assets/images/app/*')
const imgUrl: Ref<string[]> = ref([])
const getAssetsFile = (url: string, index: number) => {moudles[url]().then((res: { default: string }) => {imgUrl.value[index] = res.default})
}