view 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 source


function ajax(url,postData) {
	let request = new XMLHttpRequest();
	let method = postData ? 'POST' : 'GET';
	request.open( method, url );
	if( postData )
		request.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
	request.onload = function() {
		if( request.status !== 200 ) {
			window.console && console.log( 'ajax failed: ' + request.status );
			if( request.responseText )
				document.write('<pre>'+request.responseText+'</pre>');
			return;
		}
		eval( request.responseText );
	};
	request.send(postData);
}

window.onerror = function(msg, url, line, col, error) {
	if (!url)
		return;
	let err = msg;
	err += '\nurl = ' + url;
	if (url != window.location)
		err += '\npage = ' + window.location;
	err += '\nline = '+line;
	if (col)
		err += '\ncolumn = ' + col;
	if (error && error.stack)
		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();
}