GithubHelp home page GithubHelp logo

faizan-hassan / upload-js Goto Github PK

View Code? Open in Web Editor NEW

This project forked from bytescale/bytescale-javascript-sdk

0.0 0.0 0.0 1.32 MB

Upload.js | JavaScript File Upload Library

Home Page: https://upload.io/upload-js

License: MIT License

Shell 0.11% JavaScript 10.75% TypeScript 89.14%

upload-js's Introduction

JavaScript File Upload Library
(With Integrated Cloud Storage)



Twitter URL

Get Started — Try on CodePen

Upload.js Demo

Files Hosted on Upload.io: The File Upload Service for Developers.

Installation

Install via NPM:

npm install upload-js

Or via NPM:

yarn add upload-js

Or via a <script> tag:

<script src="https://js.upload.io/upload-js/v1"></script>

Usage

Option 1: createFileInputHandlerTry on CodePen

To implement a <input type="file" onchange=... /> handler:

import { Upload } from "upload-js";

// Get production API keys from Upload.io
const upload = new Upload({ apiKey: "free" });

// <input type="file" onchange="onFileSelected(event)" />
const onFileSelected = upload.createFileInputHandler({
  onBegin: ({ cancel }) => {
    console.log("File upload started!");
  },

  onProgress: ({ progress }) => {
    console.log(`File uploading... ${progress}%`);
  },

  onUploaded: ({ fileUrl, fileId }) => {
    console.log(`File uploaded: ${fileUrl}`);
  },

  onError: (error) => {
    console.error(`Error uploading file.`, error);
  }
});

Option 2: uploadFileTry on CodePen

To upload a file DOM object:

import { Upload } from "upload-js";

// Get production API keys from Upload.io
const upload = new Upload({ apiKey: "free" });

// <input type="file" onchange="onFileSelected(event)" />
const onFileSelected = async (event) => {
  const [ file ]    = event.target.files;
  const { fileUrl } = await upload.uploadFile({ file, onProgress });
  console.log(`File uploaded: ${fileUrl}`);
}

const onProgress = ({ progress }) => {
  console.log(`File uploading: ${progress}% complete.`)
}

Full Working Example (Copy & Paste!)

Try on CodePen / Run In Browser:

<html>
  <head>
    <script src="https://js.upload.io/upload-js/v1"></script>
    <script>
      const upload = new Upload({
        // Get production API keys from Upload.io
        apiKey: "free"
      });

      const uploadFile = upload.createFileInputHandler({
        onProgress: ({ progress }) => {
          console.log(`${progress}% complete`)
        },
        onUploaded: ({ fileUrl, fileId }) => {
          alert(`File uploaded!\n${fileUrl}`);
        },
        onError: (error) => {
          alert(`Error!\n${error.message}`);
        }
      });
    </script>
  </head>
  <body>
    <input type="file" onchange="uploadFile(event)" />
  </body>
</html>

Examples with Popular Frameworks

Upload Files with React — Try on CodePen

const { Upload } = require("upload-js");
const upload = new Upload({ apiKey: "free" });

const MyUploadButton = () => {
  const uploadFile = upload.createFileInputHandler({
    onProgress: ({ bytesSent, bytesTotal }) => {
      console.log(`${bytesSent / bytesTotal}% complete`)
    },
    onUploaded: ({ fileUrl, fileId }) => {
      alert(`File uploaded!\n${fileUrl}`);
    },
    onError: (error) => {
      alert(`Error!\n${error.message}`);
    }
  });

  return <input type="file" onChange={uploadFile} />;
};

Upload Files with Angular — Try on CodePen

const { Upload } = require("upload-js");
const upload = new Upload({ apiKey: "free" });
angular
  .module("exampleApp", [])
  .controller("exampleController", $scope => {
    $scope.uploadFile = upload.createFileInputHandler({
      onProgress: ({ bytesSent, bytesTotal }) => {
        console.log(`${bytesSent / bytesTotal}% complete`)
      },
      onUploaded: ({ fileUrl, fileId }) => {
        alert(`File uploaded!\n${fileUrl}`);
      },
      onError: (error) => {
        alert(`Error!\n${error.message}`);
      }
    });
  })
  .directive("onChange", () => ({
    link: (scope, element, attrs) => {
      element.on("change", scope.$eval(attrs.onChange));
    }
  }));

Upload Files with Vue.js — Try on CodePen

const { Upload } = require("upload-js");
const upload = new Upload({ apiKey: "free" });
const uploadFile = upload.createFileInputHandler({
  onProgress: ({ bytesSent, bytesTotal }) => {
    console.log(`${bytesSent / bytesTotal}% complete`)
  },
  onUploaded: ({ fileUrl, fileId }) => {
    alert(`File uploaded!\n${fileUrl}`);
  },
  onError: (error) => {
    alert(`Error!\n${error.message}`);
  }
});
const vueApp = new Vue({
  el: "#example",
  methods: { uploadFile }
});

Upload Files with jQuery — Try on CodePen

<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://js.upload.io/upload-js/v1"></script>
    <script>
      const upload = new Upload({
        // Get production API keys from Upload.io
        apiKey: "free"
      });

      $(() => {
        $("#file-input").change(
          upload.createFileInputHandler({
            onBegin: () => {
              $("#file-input").hide()
            },
            onProgress: ({ bytesSent, bytesTotal }) => {
              const progress = Math.round(bytesSent / bytesTotal * 100)
              $("#title").html(`File uploading... ${progress}%`)
            },
            onError: (error) => {
              $("#title").html(`Error:<br/><br/>${error.message}`)
            },
            onUploaded: ({ fileUrl, fileId }) => {
              $("#title").html(`
                File uploaded:
                <br/>
                <br/>
                <a href="${fileUrl}" target="_blank">${fileUrl}</a>`
              )
            }
          })
        )
      })
    </script>
  </head>
  <body>
    <h1 id="title">Please select a file...</h1>
    <input type="file" id="file-input" />
  </body>
</html>

Upload Multiple Files with jQuery — Try on CodePen

Please refer to the CodePen example (link above).

Overview of the code:

  1. Instantiate Upload once in your app (at the start).
  2. Call createFileInputHandler once for each file <input> element.
  3. Use onProgress to display the upload progress for each input element.
  4. When onUploaded fires, record the fileUrl from the callback's argument to a local variable.
  5. When onUploaded has fired for all files, the form is ready to be submitted.

Note: file uploads will safely run in parallel, despite using the same Upload instance.

Force File Downloads

By default, the browser will attempt to render uploaded files:

https://upcdn.io/W142hJkHhVSQ5ZQ5bfqvanQ

To force a file to download, add ?download=true to the file's URL:

https://upcdn.io/W142hJkHhVSQ5ZQ5bfqvanQ?download=true

Resize Images

Given an uploaded image URL:

https://upcdn.io/W142hJkHhVSQ5ZQ5bfqvanQ

Resize with:

https://upcdn.io/W142hJkHhVSQ5ZQ5bfqvanQ/thumbnail

Auto-crop with:

https://upcdn.io/W142hJkHhVSQ5ZQ5bfqvanQ/thumbnail-square

Tip: to create more transformations, please register an account.

Crop Images — Try on CodePen

To crop images using manually-provided geometry:

<html>
  <head>
    <script src="https://js.upload.io/upload-js/v1"></script>
    <script>
      const upload = new Upload({
        // Get production API keys from Upload.io
        apiKey: "free"
      });

      // Step 1: Upload the original file.
      const onOriginalImageUploaded = ({ fileId, fileUrl: originalImageUrl }) => {

        // Step 2: Configure crop geometry.
        const crop = {
          // Type Def: https://github.com/upload-io/upload-image-plugin/blob/main/src/types/ParamsFromFile.ts
          input: fileId,
          pipeline: {
            steps: [
              {
                geometry: {
                  // Prompt your user for these dimensions...
                  offset: {
                    x: 20,
                    y: 40
                  },
                  size: {
                    // ...and these too...
                    width: 200,
                    height: 100,
                    type: "widthxheight!"
                  }
                },
                type: "crop"
              }
            ]
          }
        }

        // Step 3: Upload the crop geometry.
        const blob = new Blob([JSON.stringify(crop)], {type: "application/json"});
        upload
          .uploadFile({
            file: {
              name: `${fileId}_cropped.json`, // Can be anything.
              type: blob.type,
              size: blob.size,
              slice: (start, end) => blob.slice(start, end)
            }
          })
          .then(
            ({ fileUrl: cropGeometryUrl }) => {

              // Step 4: Done! Here's the cropped image's URL:
              alert(`Cropped image:\n${cropGeometryUrl}/thumbnail`)

            },
            e => console.error(e)
          );
      };

      const uploadFile = upload.createFileInputHandler({
        onUploaded: onOriginalImageUploaded
      });
    </script>
  </head>
  <body>
    <input type="file" onchange="uploadFile(event)" />
  </body>
</html>

📖 Documentation

See Upload.js Documentation »

🎯 Features

Upload.js is the JavaScript client library for Upload.io: the file upload service for developers.

Core features:

  • File Storage. (Files stored for 4 hours with the "free" API key.)
  • File Hosting via CDN. (Files served from 100 locations worldwide.)
  • Fast Image Transformations. (Resize images, crop images & convert images.)

Available with an account:

  • Permanent Storage. (The "free" API key provides temporary storage only.)
  • Unlimited Daily Uploads. (The "free" API key allows 100 uploads per day per IP.)
  • Extended CDN Coverage. (Files served from 300+ locations worldwide.)
  • More File Transformations. (Custom image resizing, cropping, converting, etc.)
  • Upload & Download Authentication. (Supports federated auth via your own JWT authorizer.)
  • File & Folder Management.
  • Expiring Links.
  • Custom CNAME.
  • Advanced Upload Control:
    • Rate Limiting.
    • Traffic Limiting.
    • File Size Limiting.
    • IP Blacklisting.
    • File Type Blacklisting.
    • And More...

Create an Upload.io account »

Need a File Upload Widget?

See Uploader »

Uploader is a lightweight file upload widget, powered by Upload.js:

Upload.js Demo

Building From Source

Please read: BUILD.md

Contribute

If you would like to contribute to Upload.js:

  1. Add a GitHub Star to the project (if you're feeling generous!).
  2. Determine whether you're raising a bug, feature request or question.
  3. Raise your issue or PR. 🚀

License

MIT

upload-js's People

Contributors

ljwagerfield avatar bytescale-service-account avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.