getUploadUrl doesn't return a token

Function getUploadUrl( )

Gets an upload URL with a token.
But that backend module

import { mediaManager } from 'wix-media-backend';

export function getUploadUrl() {
  return mediaManager.getUploadUrl(
    "/uploadfolder/uploadbygetUploadUrl",
    {
      "mediaOptions": {
        "mimeType": "image/jpeg",
        "mediaType": "image"
      },
      "metadataOptions": {
        "isPrivate": false,
        "isVisitorUpload": false,
        "context": {
        }
      }
    }
  );
}

returns only uploadUrl,
like https://upload.wixmp.com/upload/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
and uploadToken is undefined.

Is this a bug? Or this is an optional value and is not needed for uploading a file by POST?

Thanks for the help.

1 Like

Following the progress…

So the token is only required if you’ve set your Upload URL to be for private files, that aren’t public to visitors. Once you have created a URL for public files for upload, you can use just the url that’s passed back.

When you’re creating your form data, you simply add the token as an empty string (“”). I should have some working code that I can share with you later from a live site.

@chris-derrell

I should have some working code
That will be great!

About token - I have just set the

        "isPrivate": true,

and still no token returned.

Again, with that code in html component


<html>
<head>
    <script type="text/javascript">
    var openFile = function(event) {
    var msg = {fileName:"", fileType:"", content:"", fileSize:"", accepted:""};
    var input = event.target; 
    var reader = new FileReader();
    var fileName = input.files[0].name;   
    var fileType = input.files[0].type; 
    var fileSize = input.files[0].size;
    var accepted = input.accept;

    reader.readAsArrayBuffer(input.files[0]);

    reader.onloadend = function sendmsg(){
      var buffer = reader.result;   
      msg.fileName = fileName; 
      msg.content = buffer; 
      msg.fileType = fileType;
      msg.fileSize = fileSize;
      msg.accepted = accepted;
      window.parent.postMessage(msg,"*");
    };
    window.onmessage = (event) => {
    var url = event.data;
    var formData = {
          upload_token: "",
    file: {
      value: msg.content, 
      options: {
        filename: msg.fileName,
        contentType: msg.fileType
      }
    }
  };
    console.log(formData);
    let request = new XMLHttpRequest();
    request.open("POST", url);
    request.send(formData);
  };
  };

  </script>
  </head>

<body>
<label class="custom-file-upload" >
   <input type="file" accept='image/*' onchange='openFile(event)' />
  </label>
</body>
</html>

I get this at console

What was the code you used to generate the upload URL?

@chris-derrell

that backend module

import { mediaManager } from 'wix-media-backend';
6
7export function getUploadUrl() {
8  return mediaManager.getUploadUrl(
9    "/myUploadFolder/subfolder",
10    {
11      "mediaOptions": {
12        "mimeType": "image/jpeg",
13        "mediaType": "image"
14      },
15      "metadataOptions": {
16        "isPrivate": false,
17        "isVisitorUpload": false,
18        "context": {
19          "someKey1": "someValue1",
20          "someKey2": "someValue2"
21        }
22      }
23    }
24  );
25}

@ab4583325 Ok got it.

I’ve attached the snippet of code that I used for a website for the upload. I realized a difference was what I used for the file, which in my code I named targetFile . It looks as if I used the direct file object for the upload, and it worked. I’ll explain how you can edit yours to work as well.

/** My Code Snippet - I wrote mine in a custom element **/

//Snippet of code for the upload
try {
            const upload_url = this.getAttribute('upload_url');
            console.log("Retrieved upload URL in Custom Element")
            console.log(upload_url)
            if (upload_url != null) {
                const formData = new FormData();

                formData.append('upload_token', this.hasAttribute('upload_token') ? this.getAttribute('upload_token') : "");
                // targetFile = this.targetInput.files[0];
                formData.append('file', targetFile);

                let request = new XMLHttpRequest();
                request.open('POST', upload_url);

                request.send(formData);
            }

        } catch (err) {
            //These were error messages I had for the custom element's getAttribute method. You can ignore them.
            console.error("Error occured retrieving upload token: " + err);
            throw Error("Error occured retrieving upload token: " + err);

        };

/** How you could edit your own code **/

  1. Instead of creating your own FormData JSON object, try using the native JavaScript FormData object.

const formData = new FormData();

  1. Instead of recreating the file parameter in the formData, use the native File object that’s returned from the event parameter.

event.target.input.files[0]

I’m not sure I see any other big differences in our code, you can look through and let me know.

By the way, love how you’re pushing through to make this happen. You’re close. :muscle:t4:

@chris-derrell

You’re close. :muscle:t4:
Nothing motivates me better than these words of yours :slight_smile: Thanks Chris)))
In the near future I will try to figure it out!

@ab4583325 This may also help you → generating your END-SOLUTION :wink:

https://russian-dima.wixsite.com/login-system/upload-url

@russian-dima

Thanks for this! I’ve seen your site before and you are doing a great job for the community!

@ab4583325
Sorry if the example do not work sometimes → in developement!:wink:

You are very close! VERY VERY close!

  1. Click on File-Selector and choose your file…
  2. If you want just to see the UPLOAD-URL → click on → “Get UPLOAD-URL”
  3. Take a look onto all console-logs (example & system console-logs)
  4. Read the additional informations in one of the links i provided…


Perhaps Chris can give you one more hint… perhaps you even do not need any hints anymore… who knows…

At current time, this is my output in my CONSOLE…

So still a little bit buggy!:sweat_smile:

We are getting clooooooooooser :roll_eyes::rofl::yum::stuck_out_tongue_winking_eye:

Front:

import {getUploadUrl} from 'backend/getUploadUrl.jsw'

$w.onReady(async()=>{   
    $w('#html1').onMessage((msg)=>{console.log(msg);
        $w('#txtFileName').text = msg.data.fileName; $w('#checkFileName').show();
        $w('#txtFileType').text = msg.data.fileType; $w('#checkFileType').show();
        $w('#txtFileSize').text = String(msg.data.fileSize); $w('#checkFileSize').show();
        $w('#txtBufferType').text = "ArrayBuffer"; $w('#checkBufferType').show();
        $w('#txtConsoleUpload').text = "-------------------------------------->"    
        get_uploadURL();    
    });

    $w('#btnGetUploadURL').onClick(async()=>{get_uploadURL();});

    async function get_uploadURL(){
        let uploadDATA = await getUploadUrl(); console.log("UPLOAD-DATA: ", uploadDATA);
        let urlToken = uploadDATA.uploadToken; console.log("URL-TOKEN: ", urlToken);
        let uploadURL = uploadDATA.uploadUrl;  console.log("UPLOAD-URL: ", uploadURL);
        $w('#txtUploadURL').text = uploadDATA.uploadUrl;    $w('#checkUrlUpload').show();
        if(urlToken) {$w('#txtURLtoken, #txtConsoleToken').text = uploadDATA.uploadToken;}
        else {$w('#txtURLtoken, #txtConsoleToken').text = "Token --> EMPTY !!!";}
        $w('#checkUrlToken').show();
        $w('#html1').postMessage(uploadURL);
    }
});

Back: (getUploadUrl.jsw)

import { mediaManager } from 'wix-media-backend';

export function getUploadUrl() {
  return mediaManager.getUploadUrl(
    "/myUploadFolder/subfolder",
    {
      "mediaOptions": {
        "mimeType": "image/png",
        "mediaType": "image"
      },
      "metadataOptions": {
        "isPrivate": false,
        "isVisitorUpload": false,
        "context": {
          "someKey1": "someValue1",
          "someKey2": "someValue2"
        }
      }
    }
  );
}

I think that must be the very last step! We are already on the execution :wink:

Now —> It’s your turn !

<html>
  <head>
    <script type="text/javascript">    
    
    var openFile = function(event) {
      var msg = {fileName:"", fileType:"", content:"", fileSize:"", accepted:""};
      var input = event.target;                 console.log(input);
      var fileName = input.files[0].name; 	console.log("File-Name: ", fileName);
      var fileType = input.files[0].type;       console.log("File-Type: ", fileType);
      var fileSize = input.files[0].size;  	console.log("File-Size: ", fileSize);
      var accepted = input.accept;		console.log("Accepted: ", accepted);
      //-------------------------------------------------------------------------------
      var buffer, reader = new FileReader();	//console.log(reader);
      reader.readAsArrayBuffer(input.files[0]);	 
      reader.onloadend = function sendmsg(){
        buffer = reader.result;  		console.log("Buffer: ", buffer); 
        msg.fileName = fileName; 
        msg.content = buffer; 
        msg.fileType = fileType;
        msg.fileSize = fileSize;
        msg.accepted = accepted;
        window.parent.postMessage(msg,"*");
      };   
    //-----------------------------------    
    window.onmessage = (async(event) => {
      var uploadURL = event.data;	  console.log("Recieved-Upload-URL: ", uploadURL);       
      var formData = await new FormData(); console.log("Form-Data: ", formData);
      formData.append(fileName, buffer, fileName); 
      let request = await new XMLHttpRequest();
      request.open("POST", uploadURL);
      request.send(formData);
    });
    //-----------------------------------  
  };
  </script>
</head>
<body>
<label class="custom-file-upload" >
   <input type="file" accept='image/*' onchange='openFile(event)' />
  </label>
</body>

</html>

OK! IT’s DONE !!!

HOUSTEN —> We reached the moon!

The PIC is in the FOLDER !

Take a look onto the provided suggestions of Chris-Derell!
Chris → you did it :wink:
(by the way, this one was much more simple than my last one with the “Buffer-Post”)

The only thing → how to change FOLDER ? And what about → Multi-Upload?
myUploadFolder/subfolder/myPic.*(png/jpeg/jpg/bmp…whatever


Send me a pic into my subfolder xDDDD and i tell you if it works :wink:

MULTI-UPLOAD on UNLIMITED FILES ? → Next-Project??? Who knows xD

Who ever it was xDDDDD

So i assume —> you are working on —> “Print on Demand” ?

BTW: The BANANA-PIC was not that big! :wink: In this case, also my first solution would be enough :roll_eyes:

@russian-dima
Cool! I’ll check it soon!
/// mine bananas :slight_smile:

The only thing → how to change FOLDER ?
To do that you need to pass your params to backend function ( getUploadUrl.jsw ) from the front

front

import {getUploadUrl} from 'backend/getUploadUrl';

export function upload01btn_click(event) {
          let userPicFolder = $w("#input").value;
          getUploadUrl(userPicFolder)
          .then (() => {
            /// some code
            console.log();
          }
}

back

import { mediaManager } from 'wix-media-backend';

export function getUploadUrl(userPicFolder) { 
return mediaManager.getUploadUrl(`/myUploadFolder/${userPicFolder}`,
{"mediaOptions": 
{"mimeType": "image/png",
"mediaType": "image"},
"metadataOptions": 
{"isPrivate": false, 
"isVisitorUpload": false, 
"context": {
"someKey1": "someValue1", 
"someKey2": "someValue2"
}
}
}
);
}

You’re close) graphic design and other things)

@ab4583325 Nice!