(function() { 'use strict'; var itemId = document.getElementById('wizard-item-content-file-cfg').dataset.itemId; var dropArea = document.getElementById('file-upload-area'); var fileInput = document.getElementById('file-input'); var statusEl = document.getElementById('file-upload-status'); initDropzone(dropArea, fileInput, function(file) { uploadFile(file); }); function uploadFile(file) { var contentType = file.type || 'application/octet-stream'; statusEl.innerHTML = '
' + '
' + '' + '0%
' + '
' + '
'; var uploader = new S3Uploader({ filenameEl: document.getElementById('file-upload-filename'), percentEl: document.getElementById('file-upload-percent'), progressBar: document.getElementById('file-progress-bar'), }); // Create version then upload fetch('/api/items/' + itemId + '/versions', { method: 'POST', headers: Object.assign({'Content-Type': 'application/json'}, csrfHeaders()), body: JSON.stringify({ version_number: '1.0', changelog: null }) }) .then(function(res) { if (!res.ok) return res.json().catch(function() { return {}; }).then(function(d) { throw new Error(d.error || 'Failed to create version'); }); return res.json(); }) .then(function(verData) { return fetch('/api/versions/' + verData.id + '/upload/presign', { method: 'POST', headers: Object.assign({'Content-Type': 'application/json'}, csrfHeaders()), body: JSON.stringify({ file_name: file.name, content_type: contentType }) }).then(function(res) { if (!res.ok) return res.json().catch(function() { return {}; }).then(function(d) { throw new Error(d.error || 'Failed to get upload URL'); }); return res.json(); }).then(function(data) { return uploader.upload(data.upload_url, file, data.s3_key, contentType, data.cache_control) .then(function(s3Key) { return { s3Key: s3Key, versionId: verData.id }; }); }); }) .then(function(result) { return fetch('/api/versions/' + result.versionId + '/upload/confirm', { method: 'POST', headers: Object.assign({'Content-Type': 'application/json'}, csrfHeaders()), body: JSON.stringify({ s3_key: result.s3Key, file_size_bytes: file.size }) }); }) .then(function(res) { if (!res.ok) return res.json().catch(function() { return {}; }).then(function(d) { throw new Error(d.error || 'Failed to confirm upload'); }); statusEl.innerHTML = '
Upload complete.
'; }) .catch(function(err) { // Server error text is set via textContent, not innerHTML, so a // message echoed from an API response can't inject markup. var msg = document.createElement('div'); msg.className = 'upload-status-msg is-error'; msg.textContent = err.message || 'Upload failed'; statusEl.replaceChildren(msg); }); } })();