1.3.12. fejezet, Kép továbbítása WebSocket-en át REST API felé

WebSocket szerver oldali TypeScript

       ws.on('message', function incoming(message: string) {
		console.log('received: %s', message);
		var mObj = JSON.parse(message);
		if (mObj.action == 'scan') {
			try {
				const fileName = scanImage(mObj.color_mode, mObj.resolution);
				const content = fs.readFileSync(fileName);
				const imageData = new Uint8Array(content);
				ws.send(new Blob([imageData], { type: 'image/jpg' }));
				if (fs.existsSync(fileName)) fs.unlinkSync(fileName);
			} catch (e) {
				console.log(e);
				ws.send(e);
			}
		}
	});

WebScoket kliens és böngésző oldali funkciók

        var data, websocket;
 
        function init() {
            websocket = new WebSocket(wsUri);
 
            websocket.onmessage = function (e) {
                if (e.data instanceof Blob) {
                    var reader = new FileReader();
                    reader.addEventListener('loadend', () => {
                        data = reader.result;
                        image.src = data;
                    });
                    reader.readAsDataURL(e.data);
                } else {
                    writeToScreen('<span>RESPONSE: ' + e.data + '</span>');
                }
            }
        }
        function sendButtonOnClick() {
            if (data) {
                sendImageAsPostRequest(
                    data.split(',')[1],
                    'image/jpg',
                    '/api/file/uploadimage',
                );
            } else {
                alert('Nincs beolvasott elmenthető kép!')
            }
        }
 
        function decodeBase64(base64Data) {
            return atob(base64Data);
        }
 
        function convertToUint8Array(binaryData) {
            const bytes = new Uint8Array(binaryData.length);
            for (let i = 0; i < binaryData.length; i++) {
                bytes[i] = binaryData.charCodeAt(i);
            }
            return bytes;
        }
 
        function createBlobFromBase64(base64Data, mimeType) {
            const binaryData = decodeBase64(base64Data);
            const uint8Array = convertToUint8Array(binaryData);
            return new Blob([uint8Array], { type: mimeType });
        }
 
        async function sendImageAsPostRequest(base64Data, mimeType, url) {
            const imageBlob = createBlobFromBase64(base64Data, mimeType);
            const formData = new FormData();
            formData.append('file',imageBlob,'scanned.jpg');
            formData.append('docid', JSON.parse(docinfo).id);
            formData.append('openPaint', openPaintCheckBox.checked);
            try {
                const response = await fetch(url, {
                    method: 'POST',
                    body: formData,
                });
 
                if (response.ok) {
                    console.log('Image uploaded successfully');
                    window.close();
                } else {
                    console.error('Error uploading image:', response.status);
                    alert("Error uploading image:" + response.status);
                }
            } catch (e) {
                console.log(e);
            }
        }

Fogadó SpringBoot szerver

    @RequestMapping(value = arrayOf("/uploadimage"), method = arrayOf( RequestMethod.POST ), consumes = arrayOf(MediaType.MULTIPART_FORM_DATA_VALUE ))
    fun uploadScannedImage(@RequestPart(name = "file") file: MultipartFile, @RequestPart(name = "docid") docid: String, @RequestPart(name = "openPaint") openPaint: String) {
...
  }