javascriptreactjsfilefilereader

javascript file reader urls are absurd am i suposted to store all of that in a db?


i want to give the user the download url once they have bought the images and here's my code :

  const get_file_url = (file: File) => {
    return new Promise((acc, err) => {
      const reader = new FileReader()
      reader.onload = (event) => {
        acc(event.target?.result)
      }
      reader.onerror = (error) => {
        err(error)
      }
      reader.readAsDataURL(file)
    })
  }

you just pass it a file and it creates the url fine right, No the urls are huge (mK4EFLV700MChmzwBsU+9yyY8n86Lu'... 36363 more characters) around 35k character per image, and i don't think i should be storing allat in a db i don't even think i could if i wanted what do i do ?

Expected: a much shorter url


Solution

  • The readAsDataURL function includes the file data encoded in base 64 in the URL that it returns: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

    As you note, that is probably not what you want. How you offer the user a URL to a file will depend on what storage mechanism is actually used for the files: filesystem, database, etc. Is the argument to get_file_url namely (file: File) accessible by a URL already? Or is it stored in a non-publicly-accessible location?

    Whether it's on the filesystem in an obscure but public location, in a non-public location, or in a database, you could write a protected server route at a short, parameterized URL that maps some hash ID to the file path/database BLOB. Then, after authorization and lookup of the file path by hash or by query, serve the file as an HTTP response with appropriate headers.