File upload with PUT in Javascript

TL;DR

A little snippet that will be useful… future me!

I had some trouble assembling this from around the net, though it ended up to be quite straightforward eventually.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
<!DOCTYPE html>
<html lang="it">
   <head>
      <title>Upload with PUT</title>
      <script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
   </head>
   <body>
      <label for="customFile"
         x-data="{
            file: null,
            myfile: '',
            message: '',
            show_select: true,
            show_send: false,
            async sendFile() {
               file = this.file;
               this.file = null;
               this.show_select = false;
               this.show_send = false;
               this.message = 'Carico il file...';
               response = await (await fetch('http://api.example.com/something', {
                  method: 'PUT',
                  body: file,
                  headers: {'Content-Type': 'application/octet-string'},
               }));
               if (response.ok) {
                  this.message = 'Upload completed';
               }
               else {
                  this.message = 'Upload failed!!!';
               }
               outerthis = this;
               setTimeout(
                  function(){
                     outerthis.message = '';
                     outerthis.show_select = true;
                  }, 3000);
            },
         }">
         <input type="file" style="display: none" id="customFile"
            x-on:change="file = Object.values($event.target.files)[0]; show_send = true">
         <span x-show="show_select" x-transition x-text="file ? file.name : 'Click to select a file...'"></span>
         <button x-show="show_send" x-transition x-on:click="sendFile()">Send</button>
         <span x-text="message"></span>
      </label>
   </body>
</html>

The whole use of Alpine.js is because I’m experimenting a bit…

Stay safe everyone!


Comments? Octodon, , GitHub, Reddit, or drop me a line!