Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

WeChat Mini Program Network, Multimedia, and File APIs Overview

Tech 2

Network APIs

The WeChat Mini Program platform provides 10 network-related APIs for handling URL requests, file uploads/downloads, and WebSocket communciation:

  1. wx.request(Object) – Initiates an HTTPS request.
  2. wx.uploadFile(Object) – Uploads local resources to a server.
  3. wx.downloadFile(Object) – Downloads files from a server to the local device.
  4. wx.connectSocket(Object) – Creates a WebSocket connection.
  5. wx.sendSocketMessage(Object) – Sends data through a WebSocket connection.
  6. wx.closeSocket(Object) – Closes a WebSocket connection.
  7. wx.onSocketOpen(Callback) – Listens for WebSocket open events.
  8. wx.onSocketError(Callback) – Listens for WebSocket errors.
  9. wx.onSocketMessage(Callback) – Listens for messages received via WebSocket.
  10. wx.onSocketClose(Callback) – Listens for WebSocket close events.

Making HTTP Requests

Use wx.request() to interact with remote servers. Example: fetching HTML from Baidu (requires adding https://www.baidu.com to the request domain whitelist in the Mini Program admin panel).

<!-- pages/api/api.wxml -->
<button type="primary" bindtap="fetchBaiduHtml">Fetch HTML</button>
<textarea value="{{html}}" auto-height maxlength="0" />
Page({
  data: { html: '' },
  fetchBaiduHtml() {
    const self = this;
    wx.request({
      url: 'https://www.baidu.com',
      header: { 'Content-Type': 'application/json' },
      success(res) {
        self.setData({ html: res.data });
      }
    });
  }
});

Another example: querying postal code information via a third-party API using both GET and POST methods.

<view>Postal Code:</view>
<input type="text" bindinput="onInput" placeholder="6-digit code" />
<button type="primary" bindtap="searchAddress">Search</button>
<block wx:for="{{address}}">
  <block wx:for="{{item}}">
    <text>{{item}}</text>
  </block>
</block>
Page({
  data: {
    postcode: '',
    address: [],
    errMsg: '',
    error_code: -1
  },
  onInput(e) {
    this.setData({ postcode: e.detail.value });
  },
  searchAddress() {
    const { postcode } = this.data;
    if (!postcode) return;

    wx.showToast({ title: 'Searching...', icon: 'loading', duration: 10000 });
    wx.request({
      url: 'https://v.juhe.cn/postcode/query',
      data: {
        postcode,
        key: '0ff9bfccdf147476e067de994eb5496e'
      },
      method: 'GET', // or 'POST'
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        wx.hideToast();
        if (res.data.error_code === 0) {
          this.setData({
            address: res.data.result.list,
            errMsg: '',
            error_code: 0
          });
        } else {
          this.setData({
            errMsg: res.data.reason,
            error_code: res.data.error_code
          });
        }
      }
    });
  }
});

Uploading Files

Use wx.uploadFile() to send local files (e.g., images) to a server.

<button type="primary" bindtap="uploadImage">Upload Image</button>
<image src="{{previewUrl}}" mode="widthFix" />
Page({
  data: { previewUrl: null },
  uploadImage() {
    wx.chooseImage({
      success: (res) => {
        const filePath = res.tempFilePaths[0];
        wx.showToast({ title: 'Uploading...', icon: 'loading' });
        wx.uploadFile({
          url: 'http://localhost/upload',
          filePath,
          name: 'file',
          success: (uploadRes) => {
            if (uploadRes.statusCode !== 200) {
              wx.showModal({ title: 'Error', content: 'Upload failed', showCancel: false });
              return;
            }
            this.setData({ previewUrl: filePath });
          },
          fail: () => {
            wx.showModal({ title: 'Error', content: 'Upload failed', showCancel: false });
          },
          complete: wx.hideToast
        });
      }
    });
  }
});

Downloading Files

Use wx.downloadFile() to retrieve files (e.g., images) from a server.

<button type="primary" bindtap="downloadImage">Download Image</button>
<image src="{{imgSrc}}" style="width:90%; height:500px;" mode="widthFix" />
Page({
  data: { imgSrc: null },
  downloadImage() {
    wx.downloadFile({
      url: 'http://localhost/1.jpg',
      success: (res) => {
        this.setData({ imgSrc: res.tempFilePath });
      }
    });
  }
});

Multimedia APIs

These APIs enhance user interaction through media handling.

Image APIs

  • wx.chooseImage() – Select images from album or take photos.
  • wx.previewImage() – Preview images in full screen.
  • wx.getImageInfo() – Get image metadata (width, height, etc.).
  • wx.saveImageToPhotosAlbum() – Save image to device photo library (requires user permission).

Example: choosing and saving an image.

wx.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success(res) {
    const path = res.tempFilePaths[0];
    wx.saveImageToPhotosAlbum({
      filePath: path,
      success() { console.log('Saved!'); }
    });
  }
});

Audio Recording APIs

  • wx.startRecord() – Begin recording audio (max 1 minute).
  • wx.stopRecord() – Stop recording manually.

Recorded files are temporary; use wx.saveFile() to persist them.

wx.startRecord({
  success(res) {
    const tempPath = res.tempFilePath;
    setTimeout(() => wx.stopRecord(), 10000);
  }
});

Voice Playback APIs

  • wx.playVoice() – Play a voice file.
  • wx.pauseVoice() – Pause playback.
  • wx.stopVoice() – Stop and reset playback.

Only one voice can play at a time.

wx.startRecord({
  success(res) {
    const path = res.tempFilePath;
    wx.playVoice({ filePath: path });
    setTimeout(() => wx.pauseVoice(), 5000);
  }
});

Background Music APIs

Supports streaming audio only (no local files). Key APIs:

  • wx.playBackgroundAudio() – Start playback.
  • wx.getBackgroundAudioPlayerState() – Get current state (position, duration, etc.).
  • wx.seekBackgroundAudio() – Jump to a specific time.
  • wx.pauseBackgroundAudio() / wx.stopBackgroundAudio() – Control playback.
  • Event listeners: onBackgroundAudioPlay, onBackgroundAudioPause, onBackgroundAudioStop.

Example Music Player:

<!-- music.wxml -->
<view class="container">
  <image class="cover" src="{{showCover ? music.cover : '/images/default.png'}}" />
  <view class="controls">
    <image src="/images/rewind.png" bindtap="seek" data-offset="-10" />
    <image src="/images/{{isPlaying ? 'pause' : 'play'}}.png" bindtap="togglePlay" />
    <image src="/images/stop.png" bindtap="stopMusic" />
    <image src="/images/forward.png" bindtap="seek" data-offset="10" />
  </view>
</view>
/* music.wxss */
.cover { width: 350rpx; height: 350rpx; margin-bottom: 100rpx; }
.controls image { width: 64rpx; height: 64rpx; margin: 30rpx; }
// music.js
Page({
  data: {
    isPlaying: false,
    showCover: false,
    music: {
      url: 'https://example.com/song.mp3',
      title: 'Sample Song',
      cover: 'https://example.com/cover.jpg'
    }
  },
  onLoad() {
    this.setupAudioListeners();
  },
  togglePlay() {
    if (this.data.isPlaying) {
      wx.pauseBackgroundAudio();
    } else {
      const { url, title, cover } = this.data.music;
      wx.playBackgroundAudio({ dataUrl: url, title, coverImgUrl: cover });
    }
  },
  stopMusic() {
    wx.stopBackgroundAudio();
    this.setData({ isPlaying: false, showCover: false });
  },
  seek(e) {
    const offset = parseInt(e.currentTarget.dataset.offset);
    wx.getBackgroundAudioPlayerState({
      success(res) {
        if (res.status === 1) {
          let pos = res.currentPosition + offset;
          pos = Math.max(1, Math.min(pos, res.duration - 1));
          wx.seekBackgroundAudio({ position: pos });
          wx.showToast({ title: offset > 0 ? 'Forward 10s' : 'Rewind 10s', duration: 500 });
        } else {
          wx.showToast({ title: 'Not playing', duration: 800 });
        }
      }
    });
  },
  setupAudioListeners() {
    wx.onBackgroundAudioPlay(() => this.setData({ isPlaying: true, showCover: true }));
    wx.onBackgroundAudioPause(() => this.setData({ isPlaying: false }));
    wx.onBackgroundAudioStop(() => this.setData({ isPlaying: false, showCover: false }));
  }
});

File APIs

Used to manage persistent local storage of files (e.g., downloaded or recorded content).

  1. wx.saveFile() – Persist a temporary file.
  2. wx.getSavedFileList() – List all saved files.
  3. wx.getSavedFileInfo() – Get metadata of a saved file.
  4. wx.removeSavedFile() – Delete a saved file.
  5. wx.openDocument() – Open documents (PDF, DOCX, XLSX, PPTX, etc.) in a new page.

Saving a File

wx.chooseImage({
  success(res) {
    wx.saveFile({
      tempFilePath: res.tempFilePaths[0],
      success(saveRes) {
        console.log('Saved to:', saveRes.savedFilePath);
      }
    });
  }
});

Managing Saved Files

// List files
wx.getSavedFileList({
  success(res) {
    console.log(res.fileList);
  }
});

// Get file info
wx.getSavedFileInfo({
  filePath: 'some_saved_path',
  success(info) {
    console.log('Size:', info.size);
  }
});

// Delete file
wx.getSavedFileList({
  success(res) {
    if (res.fileList.length > 0) {
      wx.removeSavedFile({
        filePath: res.fileList[0].filePath
      });
    }
  }
});

Opening Documents

wx.downloadFile({
  url: 'http://localhost/report.pdf',
  success(res) {
    wx.openDocument({
      filePath: res.tempFilePath,
      success() { console.log('Document opened'); }
    });
  }
});

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.