Search code examples
javascriptdropbox

Why is my function not defined when it's called?


I am trying to upload a file on Dropbox using the JS SDK. Here is the html code where I try to call my function :

<!DOCTYPE html>
<html>
<head>
    <script src="get_from_cin7.js"></script>
    <meta charset="utf-8" />
    <title>Dropbox JavaScript SDK</title>
    <!--<link rel="stylesheet" href="/styles.css">-->
</head>
<body>
    <form onSubmit="Dropupload()">
        <input type="file" id="file-upload" />
        <button type="submit">Submit</button>
      </form>
</body>
</html>

And here's the file where the function is defined

import { Dropbox } from 'dropbox';

const dbx = new Dropbox({
    accessToken: '<ACCESS TOKEN>', //I replaced it with my access token in the code
    fetch
});

function Dropupload() {
    var file = fileIput.files[0];
    dbx.filesUpload({path: '/' + file.name, contents: file})
    .then(function(response) {
        var results = document.getElementById('results');
        results.appendChild(document.createTextNode('File uploaded!'));
        document.write('MISSION COMPLETE');
      })
      .catch(function(error) {
        console.error(error);
        document.write('BETTER LUCK NEXT TIME');
      });
}

Still, my function cannot be called for some reason I don't know. I get the error "ReferenceError: Dropupload is not defined" and I don't know if that has something to do with the problem but I get another error : "SyntaxError: import declarations may only appear at top level of a module".

I'm just going to test the upload so that's the whole code for now.

What exactly is the problem here ?


Solution

  • You forgot type="module" in the script tag. The ES6 modules syntax won't work if you don't do that.

    You also need to attach Dropupload to window, otherwise it is local to the module.

    window.Dropupload = function() {
      var file = fileIput.files[0];
      ...