I need a way to generate a .txt file with javascript code and make it downloadable to the user.
I also need a way to get a .txt file uploaded by the user and read it.
I tried messing around with a dataset but couldn’t get it to work.
How should I approach this?
Thanks for the help and sorry if the topic has already been covered
"I also need a way to get a .txt file uploaded by the user and read it. "
Do you mean the system should read it and do something with the text? Or to let the user open the file and read it.
Answers:
Answer 1:
Install the buffer.js NPM package.
Create a .js or j.sw file (depands whter or not you wish to trigger it from the front end).
And put code like this inside (the text argument is the file body content):
import { mediaManager } from 'wix-media-backend';;
import { Buffer } from 'buffer';
export async function createTxtFile(text, memberId, fileName) {
const buffer = Buffer.from(text)
const folder = `/memberFiles/${memberId}`;
fileName += '.txt'
return mediaManager.upload(
folder,
buffer,
fileName, {
mediaOptions: {
mimeType: 'text/plain',
mediaType: 'document'
},
metadataOptions: {
isPrivate: false,
isVisitorUpload: true,
context: {
isUserFile: true,
id: memberId
}
}
}
)
.then(async txtFile => {
const wixUrl = txtFile?.fileUrl;
if (!wixUrl) { return Promise.reject('failed to create') }
const downloadUrl = await mediaManager.getFileUrl(wixUrl);
//you can run data insert to save the URLs and file details to a database collection
return { wixUrl, downloadUrl };
})
.catch(err => {
console.log("<<<<<<failed to upload text>>>>>>>>", err);
return err;
});
}
Answer 2:
Add an upload button to the page, restrict it to “document”, upload it, and once uploaded, save the data to the collection.
Answer 3:
Use mediaManager.getFileUrl(wixUrl). And if you saved the downloadable url in the database, just use it (for example link it to a button).
Answer 4:
Use wix-fetch with the https url of the file.
import {fetch} from 'wix-fetch';
export function readFile(url){
return fetch(url).then(res => res.text())
.then(text => {
console.log(text);
})
}