Mercurial Hosting > freedit
diff src/site.js @ 34:c8d47981c74f
upload using ajax
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Tue, 02 Aug 2022 20:46:02 -0600 |
parents | 4fdc4ec0050b |
children | 1ce75c5ab0f7 |
line wrap: on
line diff
--- a/src/site.js Mon Aug 01 22:50:16 2022 -0600 +++ b/src/site.js Tue Aug 02 20:46:02 2022 -0600 @@ -3,8 +3,7 @@ let request = new XMLHttpRequest(); let method = postData ? 'POST' : 'GET'; request.open( method, url ); - let isMultipart = postData instanceof File; - if( postData && !isMultipart ) + if( postData ) request.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' ); request.onload = function() { if( request.status !== 200 ) { @@ -15,13 +14,7 @@ } eval( request.responseText ); }; - if(isMultipart) { - let formData = new FormData(); - formData.append( 'file', postData ); - request.send(formData); - } else { - request.send(postData); - } + request.send(postData); } window.onerror = function(msg, url, line, col, error) { @@ -38,3 +31,35 @@ err += '\nstack = ' + error.stack; ajax( '/error_log.js', 'err='+encodeURIComponent(err) ); }; + +function upload(input,callback) { + let file = input.files[0]; + input.value = null; + let request = new XMLHttpRequest(); + let url = 'https://upload.uploadcare.com/base/'; + request.open( 'POST', url ); + request.onload = function() { + if( request.status !== 200 ) { + let err = 'ajax failed: ' + request.status; + if( request.responseText ) { + err += '\n' + request.responseText; + document.write('<pre>'+request.responseText+'</pre>'); + } + console.log(err); + ajax( '/error_log.js', 'err='+encodeURIComponent(err) ); + return; + } + let response = JSON.parse(request.responseText); + let filename = file.name; + let url = 'https://ucarecdn.com/' + response.file + '/' + filename; + callback(url,filename); + }; + let formData = new FormData(); + formData.append( 'UPLOADCARE_PUB_KEY', 'fe3d30f3088a50941d45' ); + formData.append( 'file', file ); + request.send(formData); +} + +function fileButtonClick(button) { + button.parentNode.querySelector('input[type="file"]').click(); +}