input type="file"で写真撮影orライブラリからファイルを選択する

★完成形★

iPhone

写真またはビデオを撮る

写真を選択

ファイルを選択

 

 

Android

カメラ

メディアを選択

 

コード

 

 <template>
  <div class="root">
    isAndroid?:{{ isAndroid }}
    <div class="button1" @click="pickImagesOrSelect()">@Capacitor/Camera</div>
    <div class="button1" @click="changeFn()">input type="file"</div>
    <input type="file" @change="handleFileChange" accept="*" ref="fileInput" />
    <div class="resetButton" @click="handleClickRest">リセット</div>
    <div class="captureWrap">
      <h1>プレビュー</h1>
      <div>fileName:{{ fileName }}</div>
      <div>previewUrl:{{ previewUrl }}</div>
      <div class="capture">
        <img :src="previewUrl" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import {
  Camera,
  CameraResultType,
  CameraSource,
  ImageOptions
} from '@capacitor/camera'
// @capacitor/camera
const isAndroid = ref(false)
const pickImagesOrSelect = async () => {
  let options: ImageOptions = {
    quality: 90,
    resultType: CameraResultType.DataUrl, // 実行後のデータの種類を指定
    correctOrientation: true,
    source: CameraSource.Prompt, // 写真を撮るorライブラリから選択
    webUseInput: true
  }
  if (isAndroid.value) {
    options.source = CameraSource.Prompt
  }
  const image = await Camera.getPhoto(options)
  previewUrl.value = image.dataUrl
}
const getMobileOS = () => {
  const ua = navigator.userAgent
  return /android/i.test(ua)
}
onMounted(() => {
  isAndroid.value = getMobileOS()
})
// input type="file"
const file = ref()
const previewUrl = ref()
const fileInput = ref()
const fileName = ref()
const changeFn = () => {
  fileInput.value.click()
}
const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement
  file.value = (target.files as FileList)[0]
  fileName.value = file.value.name
  if (file.value) {
    const reader = new FileReader()
    reader.onload = (e: ProgressEvent<FileReader>) => {
      previewUrl.value = e.target?.result as string | null
    }
    reader.readAsDataURL(file.value)
  }
}
// reset
const handleClickRest = () => {
  previewUrl.value = null
  fileName.value = null
}
</script>
<style lang="scss" scoped>
.root {
  margin: 0 auto;
  width: 390px;
  position: relative;
  padding: 16px;
}
.captureWrap {
  width: 100%;
  display: flex;
  flex-flow: column;
  gap: 12px;
  .capture {
    img {
      width: 100%;
    }
  }
}
.button1 {
  background-color: #005bac;
  color: #fff;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: 32px;
  cursor: pointer;
  font-weight: bold;
}
.resetButton {
  color: #1a1c21;
  background-color: #ffcc00;
  font-weight: bold;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: 32px;
  cursor: pointer;
}
input[type='file'] {
  display: none;
}
</style>