diff src/chat.js @ 63:afd5ab5b02a2

file upload
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 05 Mar 2025 18:43:06 -0700
parents d4d154b404f8
children 6cfef9850520
line wrap: on
line diff
--- a/src/chat.js	Wed Mar 05 15:03:26 2025 -0700
+++ b/src/chat.js	Wed Mar 05 18:43:06 2025 -0700
@@ -5,6 +5,7 @@
 let eventSource;
 let lastUpdate;
 let userId;
+let filebinUrl;
 
 function evalEvent(event) {
 	// console.log(event);
@@ -288,3 +289,47 @@
 	location = `chat?with=${email}`;
 	ajax(`save_post.js?post=${currentPostId}`,`content=${encodeURIComponent(text)}`);
 }
+
+function uploadFile() {
+	document.querySelector('input[type="file"]').click();
+}
+
+function addFileUrl(url) {
+	let textarea = document.querySelector('div[input] textarea');
+	let text = textarea.value;
+	if( /\S$/.test(text) )
+		text += ' ';
+	text += url;
+	textarea.value = text;
+}
+
+function uploadToFilebin(fileName,fileContent) {
+	//console.log(fileContent.byteLength);
+	let request = new XMLHttpRequest();
+	let url = filebinUrl + fileName;
+	request.open( 'POST', url );
+	request.onload = function() {
+		if( request.status !== 201 ) {
+			let err = 'upload failed: ' + request.status;
+			if( request.responseText ) {
+				err += '\n' + request.responseText;
+			}
+			console.log(err);
+			ajax( '/error_log.js', 'err='+encodeURIComponent(err) );
+			return;
+		}
+		addFileUrl(url);
+	};
+	request.send(fileContent);
+}
+
+function loadedFile(input) {
+	let file = input.files[0];
+	input.value = null;
+	console.log(file);
+	let reader = new FileReader();
+	reader.onload = function() {
+		uploadToFilebin(file.name,reader.result);
+	};
+	reader.readAsArrayBuffer(file);
+}