微信JSSDKを使用した複数画像のアップロードでは、並列処理ではなく逐次処理が必要となります。以下に、この要件を満たすアップロード関数の実装例を示します。
var uploadedServerIds = [];
function processImageUpload(imageLocalIds) {
if (imageLocalIds.length === 0) {
$.showPreloader('データ送信中...');
$('form').submit();
return;
}
var currentImageId = imageLocalIds[0];
// iOSでのアップロード問題への対応
if (currentImageId.includes("wxlocalresource")) {
currentImageId = currentImageId.replace("wxlocalresource", "wxLocalResource");
}
wx.uploadImage({
localId: currentImageId,
isShowProgressTips: 1,
success: function(response) {
uploadedServerIds.push(response.serverId);
imageLocalIds.shift();
processImageUpload(imageLocalIds);
},
fail: function(error) {
$.alert('アップロードに失敗しました。再試行してください。');
}
});
}
画像選択機能は以下のように実装します:
$('#imageUploadContainer img').on('click', function() {
var imageElement = $(this);
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function(result) {
var selectedLocalIds = result.localIds;
imageElement.attr('src', selectedLocalIds[0]).addClass('selected');
},
fail: function(error) {
alert(JSON.stringify(error));
}
});
});
送信処理では、選択された画像のローカルIDを収集し、アップロード関数を呼び出します:
$('#submitButton').on('click', function() {
var selectedImages = $('#imageUploadContainer img.selected');
if (selectedImages.length === 0) {
$.alert('画像を選択してください');
return;
}
$.showPreloader('画像アップロード中...');
var localImageIdentifiers = [];
selectedImages.each(function() {
localImageIdentifiers.push($(this).attr('src'));
});
processImageUpload(localImageIdentifiers);
});
重要な点は、再帰的なアプローチを使用して画像を逐次処理することです。各画像のアップロード成功後に次の画像の処理を開始します。iOSデバイスでは、ローカルIDの文字列置換が必要となる場合があります。