Handling Multiple Plupload Instances with Response Differentiation
When working with multiple Plupload instances, a common challenge is distinguishing which specific instance triggered a file upload response. Without proper identification, it becomes difficult to process the uploaded files correctly in your application.
Here's a solution using AngularJS to track which file input initiated the upload process:
Seting Up Multiple Upload Instances
var fileUploader = new plupload.Uploader({
browse_button: ['primary_upload', 'secondary_upload'],
url: '/api/upload',
flash_swf_url: 'lib/moxie.swf',
silverlight_xap_url: 'lib/moxie.xap',
filters: {
max_file_size: '10mb',
mime_types: [{
title: "Image files",
extensions: "jpg,png,gif,jpeg"
}]
},
multi_selection: false,
init: {
FilesAdded: function(up, files) {
fileUploader.start();
},
FileUploaded: function(up, file, info) {
var response = JSON.parse(info.response);
if ($scope.currentInputId === 'primary_upload') {
$scope.$apply(function() {
$scope.primaryImages.push({
id: file.id,
src: response.data[0],
isDefault: !$scope.primaryImages.length
});
$scope.primaryImage = $scope.primaryImages.length > 1 ?
$scope.primaryImage : response.data[0];
});
}
if ($scope.currentInputId === 'secondary_upload') {
$scope.$apply(function() {
$scope.secondaryImages.push({
id: file.id,
src: response.data[0],
isDefault: !$scope.secondaryImages.length
});
$scope.secondaryImage = $scope.secondaryImages.length > 1 ?
$scope.secondaryImage : response.data[0];
});
}
},
Error: function(up, err) {
alert('Upload error: ' + err.message);
}
}
});
HTML File Inputs with Click Tracking
<input type="file" id="primary_upload"
name="file"
class="upload-input"
ng-click="trackUploadInput('primary_upload')">
<input type="file" id="secondary_upload"
name="file"
class="upload-input"
ng-click="trackUploadInput('secondary_upload')">
AngularJS Controller Function
$scope.trackUploadInput = function(inputId) {
$scope.currentInputId = inputId;
};
This approach allows you to track which file input was clicked before the upload completes, enabling proper handling of the response data for each specific upload instance.