DEV Community

Bennett Upfield
Bennett Upfield

Posted on

Javascript, Sql, and File Saving

Creating Files in Javascript

This post will be over creating Files in Javascript and them uploading them to an SQL database. The first step to this process is creating the file. In Javascript there is a File Object that can be used to create Files. The constructor File() takes several components.

const newFile = new File([fileData], `filename.extension`, {
            type: "filetype/filesubtype"
        })
Enter fullscreen mode Exit fullscreen mode

To create a file use the constructor in a above mentioned way where fileData can be any sort of File data you need from strings to binary, the second parameter is the filename where it is helpful to put the extension on the end, and the third parameter is the filetype and subtype. Here is a better explanation, and a list of all the possible file-types, MDN and FileTypes.

Creating The SQL Table

To store files of any type in SQL the table you create needs to have three attributes, a binary and two strings. The binary will contain all the data that the file has, the two string will be for a name and the file mime/type (mime is name for file type). Here is the table in rails

create_table :save_files do |t|
      t.binary :file_data
      t.string :file_name
      t.string :file_mime
end
Enter fullscreen mode Exit fullscreen mode

Uploading

Now to upload the files to the SQL you will have to convert the data to binary. Luckily, Javascript has an excellent function for this arrayBuffer(). Using arrayBuffer() on your previously created file you can create a promise that you can then call a second function Uint8Array on the return creating a binary data object. Then you can simply upload the file with whatever method you want to with the data from the file.

file.arrayBuffer()
   .then(r=>{
       const fileData = new Uint8Array(r)
       fetch(`whereverYouWant`,{
       method: "POST",
       headers: {
            "Content-Type" : "application/json"
       },
       body: JSON.stringify({
            file_data: fileData,
            file_name: file.name,
            file_mime: file.type,
       })
    })
Enter fullscreen mode Exit fullscreen mode

Downloading

To download the file you need to fetch the information. The only thing different from creating the file is that you will need to create an array buffer for the file data. For creating the array buffer make the length equal to the file_data length that you pulled from the SQL and then from that buffer create a new Uint8Array for the data. Then you use that Uint8Array for the date of the file you create.

const buffer = new ArrayBuffer(data.length)
const view = new Uint8Array(buffer);
// create file with view for file data and all the other info you pulled from sql
Enter fullscreen mode Exit fullscreen mode

You can then use this file in any way you like from downloading to onsite integration.

Discussion (0)