How do I send a file to a Javascript function?

0 favourites
  • 5 posts
From the Asset Store
Source File, music and art pack for Android Negotiator
  • I am trying to use an external api that sends an image file to a url but I hve no idea how I can refernce a file from construct to the javascript function.

    The js function has something like this:

    var input = document.getElementById('file_in');

    const file = input.files[0];

    var fr = new FileReader();

    ..and then goes on to perform an api call with this data.

    However, I have no idea how to pass a (binary?) file into this js script from the event sheet. Seems I can only pass in strings and numbers(?)

    ..or If its even possible at all.

    Any pointers greatly appreciated.

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • I'm still no further along with this. I seem to have hit a dead end. Here is the api js function i want to call: (Its an image recognition api that i want to upload a camera grabbed image to)

    const baseApiURL = 'https://platform.sentisight.ai/api/';
    			var token = '';
    			var predictionId;
    			var results;
    
    			function predict(my_file) {
    				token = "some token"
    				const projectId = "some id";
    				const modelName = ""some name";
    				
    				const file = my_file.files[0];
    				var fr = new FileReader();
    				fr.onload = function() {
    					results = JSON.parse(apiPostRequest('predict/' + projectId + '/' + modelName, fr.result));
    					console.log(results);
    				}
    				fr.readAsArrayBuffer(file);
    			}
    
    			function apiPostRequest(request, body) {
    				var xmlHttp = new XMLHttpRequest();
    				xmlHttp.open( "POST", baseApiURL + request, false );
    				xmlHttp.setRequestHeader('Content-Type', 'application/octet-stream');
    				xmlHttp.setRequestHeader('X-Auth-token', token);
    				xmlHttp.send(body);
    				console.log(xmlHttp.responseText);
    				return xmlHttp.responseText;
    			}

    I'm trying to pass in a file to predict(my_file) but it just wont work.

    In my event sheet i have a function that runs a piece of JS: predict(localVars.image);

    Most of the time I'm just getting:

    Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'.

    or

    TypeError: Cannot read property '0' of undefined

    And this is my event sheet :

    PS..This should probably be moved to the scripting forum.

  • SOLVED

    Through some miracle, dark magic and the process of elimination I seemed to have managed to get this working. Now i can take a picture with the camera and this image is uploaded to the Sentisight api for image recognition. A result is then returned to my device with the recognition data.

    For anyone who might need something similar in the future, here is how the successful call looks...

    The event sheet should read>>>>>>>>

    // do SentiSIght API request

    + UserMedia: On snapshot ready

    -> AJAX: Request UserMedia.SnapshotURL (tag "got_snapshot_data")

    + AJAX: On "got_snapshot_data" completed

    -> Functions: Call Do_Sensight_Request (image: UserMedia.​SnapshotURL)

    * On function 'Do_Sensight_Request'

    * Parameter 'image' (String)

    -> Run JavaScript:

    file_in= await runtime.assets.fetchBlob(localVars.image);//THIS LINE WAS THE KEY TO THE FIX

    predict();

    and then the predict function and POST request in a JS script looks like this:

    var file_in;
    const baseApiURL = "https://platform.sentisight.ai/api/";
    var token;
    
    function predict() {
    				
    
    	token = "XXXXX";
    	const projectId = "XXXX";
    
    	const modelName = "my_model_name";	
    
    	const file = file_in;
    
    	var fr = new FileReader();
    	fr.onload = function() {
    		results = JSON.parse(apiPostRequest('predict/' + projectId + '/' + modelName, fr.result));
    		console.log(results);
    		alert(results);
    
    	}	
    	fr.readAsArrayBuffer(file);
    
    }
    
    function apiPostRequest(request, body) {
    	var xmlHttp = new XMLHttpRequest();
    	xmlHttp.open( "POST", baseApiURL + request, false );
    	xmlHttp.setRequestHeader('Content-Type', 'application/octet-stream');
    	xmlHttp.setRequestHeader('X-Auth-token', token);
    	xmlHttp.send(body);
    	console.log(xmlHttp.responseText);
    	alert ("Resp :"+xmlHttp.responseText);
    	return xmlHttp.responseText;
    }
  • SOLVED

    Through some miracle, dark magic and the process of elimination I seemed to have managed to get this working. Now i can take a picture with the camera and this image is uploaded to the Sentisight api for image recognition. A result is then returned to my device with the recognition data.

    For anyone who might need something similar in the future, here is how the successful call looks...

    The event sheet should read>>>>>>>>

    // do SentiSIght API request

    + UserMedia: On snapshot ready

    -> AJAX: Request UserMedia.SnapshotURL (tag "got_snapshot_data")

    + AJAX: On "got_snapshot_data" completed

    -> Functions: Call Do_Sensight_Request (image: UserMedia.​SnapshotURL)

    * On function 'Do_Sensight_Request'

    * Parameter 'image' (String)

    -> Run JavaScript:

    file_in= await runtime.assets.fetchBlob(localVars.image);//THIS LINE WAS THE KEY TO THE FIX

    predict();

    and then the predict function and POST request in a JS script looks like this:

    > 
    var file_in;
    const baseApiURL = "https://platform.sentisight.ai/api/";
    var token;
    
    function predict() {
    				
    
    	token = "XXXXX";
    	const projectId = "XXXX";
    
    	const modelName = "my_model_name";	
    
    	const file = file_in;
    
    	var fr = new FileReader();
    	fr.onload = function() {
    		results = JSON.parse(apiPostRequest('predict/' + projectId + '/' + modelName, fr.result));
    		console.log(results);
    		alert(results);
    
    	}	
    	fr.readAsArrayBuffer(file);
    
    }
    
    function apiPostRequest(request, body) {
    	var xmlHttp = new XMLHttpRequest();
    	xmlHttp.open( "POST", baseApiURL + request, false );
    	xmlHttp.setRequestHeader('Content-Type', 'application/octet-stream');
    	xmlHttp.setRequestHeader('X-Auth-token', token);
    	xmlHttp.send(body);
    	console.log(xmlHttp.responseText);
    	alert ("Resp :"+xmlHttp.responseText);
    	return xmlHttp.responseText;
    }

    Grimmy

    I have been trying to do this for ages! Still can't seem to get it to work can you share a capx?

  • I cant share the capx but the events to do with the predict function script above look like this:

    [PREDICT]

    | Local number Variable1‎ = 0

    ----* On function 'Do_Sensight_Request'

    ----* Parameter 'image' (String)

    -----> Functions: Call Hide Results

    -----> Functions: Call Reposition Last Photo

    -----> System: Wait for previous actions to complete

    -----> System: Set isDoingPrediction to 1

    -----> LastPhoto: Load image from UserMedia.SnapshotURL (Keep current size, cross-origin anonymous)

    -----> Functions: Call AnimateSnapshot

    -----> Run JavaScript:

    file_in= await runtime.assets.fetchBlob(localVars.image);

    predict(runtime);

    // we got the data now top the loader and update

    ----* On function 'Event_Got_Data'

    -----> Run JavaScript: GetResult(runtime);

    -----> JSON: Parse JSON string returned_data

    -----> System: Set isDoingPrediction to 0

    -----> Functions: Call Update Results

    ----* On function 'Update Results'

    -----> System: Set layer "Results" Visible

    -----> System: Set layer "Loader" Invisible

    -----> ResultText_1: Set text to JSON.Get("0.label")&" : "&JSON.Get("0.score")&"%"

    -----> ResultText_2: Set text to JSON.Get("1.label")&" : "&JSON.Get("1.score")&"%"

    -----> ResultText_3: Set text to JSON.Get("2.label")&" : "&JSON.Get("2.score")&"%"

    ----* On function 'Hide Results'

    -----> System: Set layer "Loader" Visible

    -----> System: Set layer "Results" Invisible

    Hopefully that should be enough to get you through..

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)