UniApp Guide: Select Media, Capture Photos, Record Video, and Scan Codes with Ready‑to‑Copy Code

This article explains how to prioritize UniApp's built‑in APIs (uni.chooseMedia and uni.scanCode) for media selection, photo capture, video recording, and QR/barcode scanning, provides copy‑paste‑ready code snippets, permission configurations, fallback native plugins, installation steps, and common pitfalls.

liandk
liandk
liandk
UniApp Guide: Select Media, Capture Photos, Record Video, and Scan Codes with Ready‑to‑Copy Code

Overall Approach: Built‑in APIs First, Plugins as Backup

✅ Selecting images / taking photos / recording video: use uni.chooseMedia (official, recommended).

✅ Scanning QR/barcode: use uni.scanCode (official, cross‑platform).

✅ Special needs (custom camera, QR code generation): use native plugins from the UniApp plugin market such as DCamera or QRCode.

Select Images / Capture Photo / Record Video (Core: uni.chooseMedia)

1. Core API (HBuilderX 2.2.5+, works on all platforms)

// Unified entry for selecting images, taking photos, or recording video
uni.chooseMedia({
  count: 1, // maximum number of items
  mediaType: ['image', 'video'], // allowed types
  sourceType: ['album', 'camera'], // source: album or camera
  maxDuration: 30, // max video length in seconds
  camera: 'back', // use rear camera
  success: (res) => {
    // res.tempFiles is the returned file array
    const file = res.tempFiles[0];
    console.log('File path:', file.tempFilePath);
    console.log('File type:', file.fileType); // image/video
    // preview / upload
    uni.previewImage({ urls: [file.tempFilePath] });
  },
  fail: (err) => {
    uni.showToast({ title: 'Operation failed', icon: 'none' });
  }
});

2. Capture Photo Only (Camera)

uni.chooseMedia({
  mediaType: ['image'],
  sourceType: ['camera'],
  success: (res) => { /* ... */ }
});

3. Record Video Only (Camera)

uni.chooseMedia({
  mediaType: ['video'],
  sourceType: ['camera'],
  maxDuration: 15,
  success: (res) => { /* ... */ }
});

4. Manifest Permission Configuration (iOS required, Android as needed)

// app-plus → ios → privacyDescription
"privacyDescription": {
  "NSPhotoLibraryUsageDescription": "Access photo library",
  "NSCameraUsageDescription": "Access camera for photo/video",
  "NSMicrophoneUsageDescription": "Access microphone for video"
}

Scanning QR/Barcodes (Core: uni.scanCode)

1. Basic Scan (All platforms)

uni.scanCode({
  onlyFromCamera: true, // true = camera only, false allows album selection
  scanType: ['qrCode', 'barCode'], // QR code or barcode
  success: (res) => {
    uni.showToast({ title: 'Result: ' + res.result });
    console.log('Scanned content:', res.result);
  },
  fail: (err) => {
    uni.showToast({ title: 'Scan failed', icon: 'none' });
  }
});

2. Scan from Album

uni.scanCode({
  onlyFromCamera: false,
  success: (res) => { /* ... */ }
});

3. Permission Configuration (same as photo capture, requires camera permission)

Native Plugins (When Official APIs Are Insufficient)

1. Common Plugin Recommendations

DCamera : custom camera with burst mode, filters, watermark.

QRCode : generate QR codes and barcodes.

uni-media : advanced video recording with resolution and bitrate control.

uni-choose-image : compatible with older versions, replaces uni.chooseImage.

2. Plugin Installation Steps (HBuilderX)

Menu → Plugin Market → search for the plugin name (e.g., DCamera).

Click Use → select project → automatically import into nativeplugins folder.

Edit manifest.json → App Module Configuration → check the corresponding plugin.

Re‑package in the cloud (local preview will not apply the plugin).

3. Plugin Usage Example (DCamera for Photo Capture)

// Import the plugin
const DCamera = uni.requireNativePlugin('DCamera');
// Call the photo method
DCamera.takePhoto({
  quality: 90,
  saveToAlbum: true
}, (res) => {
  console.log('Photo path:', res.path);
});

Common Issues and Pitfalls

iOS Crash : Must configure privacyDescription in the manifest, otherwise the app will be rejected or crash.

Android Permissions : Add camera and storage permissions in manifest.json under app-plus → android → permissions.

H5 Limitations : On the H5 platform only uni.chooseMedia is available; native plugins are not supported.

Path Handling : tempFilePath is temporary; convert to a local path before uploading using plus.io.convertLocalFileSystemURL.

Full Page Example (Copy‑Paste Ready)

<template>
  <view class="container">
    <button @click="chooseMedia">Select Image / Photo / Video</button>
    <button @click="scanCode">Scan Code</button>
    <image v-if="imgUrl" :src="imgUrl" style="width: 200px; height: 200px; margin-top: 20rpx;"></image>
  </view>
</template>

<script>
export default {
  data() {
    return { imgUrl: '' };
  },
  methods: {
    chooseMedia() {
      uni.chooseMedia({
        count: 1,
        mediaType: ['image', 'video'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.imgUrl = res.tempFiles[0].tempFilePath;
        }
      });
    },
    scanCode() {
      uni.scanCode({
        success: (res) => {
          uni.showToast({ title: res.result });
        }
      });
    }
  }
};
</script>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

mobile developmentUniAppchooseMedianative pluginsscanCode
liandk
Written by

liandk

Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.