Access user uploaded files from backend

In my application a member can upload files which then need to be processed.

How can I open and read the files contents after the user uploaded them?

Backend Code:

import wixUsersBackend from 'wix-users-backend';
import wixData from 'wix-data'

export async function check_files() {
  console.log("Start Check");
 // Get Data
 let user = wixUsersBackend.currentUser;
 let data = await wixData.query("Aktivitaten").eq("_owner", user.id).find();

 for (let i=0; i < data["length"]; i++) {
      // I need to access the file here
      // example filename: wix:document://v1/filename_wix.gpx/original_name.gpx"
      console.log(data["items"][i])
  }
}

Thank you

Hello @juliendavid :raised_hand_with_fingers_splayed:

If the field name/key is " file ", use this code:

for (let i=0; i < data.items.length; i++) {       
      console.log(data.items[i].file)
  }

Where the (i), is the number of the current result/item, and file is the file of that current result/item.

Hope that helped~!
Ahmad

Hello Ahmad,

I tried your example but this way i can only access the file name, but I need to read the files contents.

Do you know a way to read the content of that file within Corvid?

Thanks
Julien

Yes, if you know the type of that file you can create a suitable element to display it, for example, if the file was a video, create a video player and set its video src to the file you get from the code I’ve posted before and then expand the video player, the same applies if it was an image, create an image set to be collapsed by default and if the file is an image, set the image src to that file and then expand it.

I solved it in a different way:

I used the mediaManager to generate a URL and then used fetch to download the file.

import wixUsersBackend from 'wix-users-backend';
import wixData from 'wix-data';
import { mediaManager } from 'wix-media-backend';
import {fetch} from 'wix-fetch';


export async function check() {
  console.log("Start Check");
 // Get Data
 let user = wixUsersBackend.currentUser;
 let data = await wixData.query("Collection_Name").eq("_owner", user.id).find();

 for (let i=0; i < data["length"]; i++) {
 let wix_filename = data["items"][i].file;
 let filename = wix_filename.match(/([^\/]+\.ext)\//)[1]
 let url = await mediaManager.getFileUrl(filename)
 let file = await fetch(url);
 let content = file.text()
 console.log(content)
  }
 
}

That’s great, and thank you for sharing your solution with the community :blush:

In my case I needed to allow a user to upload a text file that contained data that would later need to be used by code.
My solution
Front end:

import { storeMediaFile, getTextMedia } from 'backend/mediaFiles'

var myTestFileRef = "aSpecificDataFile";

// upload file and store it
export function submitButton_click(event) {
 if ($w("#myUploadButton").value.length > 0) { // site visitor chose a file
        console.log("Uploading " + $w("#myUploadButton").value[0].name);
        $w("#myUploadButton").startUpload()
            .then((uploadedFile) => {
                console.log("uploadedFile:",uploadedFile)
                storeMediaFile(myTestFileRef, uploadedFile).then(result => {
                    console.log("storeMediaFile result:", result);
                }).catch(err => {
                    console.log("uncaught storeMediaFile err:", err);
                })
            });
    } else { // site visitor clicked button but didn't choose a file
        console.log("Please choose a file to upload.")
    }
}

// read the saved file
export function readFile_click(event) {
    getTextMedia(myTestFileRef).then(content => {
        console.log("readFile content: ",content)
    }).catch(err => {
        console.log("readFile err:", err)
    })
}

Backend file: mediaFiles.jsw

import wixData from 'wix-data';
import { mediaManager } from 'wix-media-backend';
import { fetch } from 'wix-fetch';

const mediaFilesDb = "MediaFiles"; 

// input: mediaId from uploadedFile object returned from UploadButton.startUpload()
// returns { fileUrl } or { error }
export function getMediaFileUrl(mediaId) {
 return mediaManager.getFileUrl(mediaId).then(fileUrl => {
 return { fileUrl: fileUrl };
    }).catch(err => {
        console.log("mediaManager.getFileUrl err");
 return { error: err };
    })
}

// mediaTitle is name to be used to reference the file in the MediaFiles db
// uploadedFile is object returned by UploadButton.startUpload()
// returns { success: true } or { error: theError }
export function storeMediaFile(mediaTitle, uploadedFile) {
 // get fileUrl from backend
 return getMediaFileUrl(uploadedFile.mediaId).then(result => {
 if (result.error) {
 return { error: result.error };
        }
 const fileUrl = result.fileUrl;
 return wixData.query(mediaFilesDb).eq("title", mediaTitle).find().then(results => {
 let item = results.items[0]
 if (item) {
 // update if already in db
                    item.fileUrl = fileUrl;
                    item.fileName = uploadedFile.mediaId;
                    item.orginalFileName = uploadedFile.title;
 return wixData.update(mediaFilesDb, item).then(res => {
                        console.log("db updated:", res)
 return { fileUrl }
                    }).catch(dbErr => {
                        console.log("db err:", dbErr)
 return { error: dbErr }
                    });
                }
 // else create new record
 const newItem = { title: mediaTitle, fileUrl: fileUrl }
 return wixData.insert(mediaFilesDb, newItem).then(insertedItem => {
                    console.log("inserted:", insertedItem)
 return { fileUrl }
                }).catch(dbErr => {
                    console.log("db err:", dbErr)
 return { error: dbErr }
                });
            })
            .catch((uploadError) => {
                console.log("File upload error: ", uploadError);
 return { error: uploadError }
            });
    }).catch(err => {
        console.log("getMediaFileUrl err:", err);
 return { error: err }
    })
}

// input: mediaTitle - media reference used with storeMediaFile(mediaTitle, uploadedFile)
// returns text content of file
export function getTextMedia(mediaTitle) {
 return wixData.query(mediaFilesDb).eq("title", mediaTitle).find().then(async results => {
 let item = results.items[0]
 let content = null;
 if (item) {
 let response = await fetch(item.fileUrl);
            content = response.text()
        }
 return content
    })
}