How do I get input file path using NeutralinoJS?
My Code:
<input type="file" id="inputFile">
const inputFilePath = document.getElementById('inputFile').files[0].path
console.log(inputFilePath)
I don't think browsers allow you to get file paths.
You could use the file picker API instead os.showDialogOpen(DialogOpenOptions):
https://neutralino.js.org/docs/api/os#osshowdialogopendialogopenoptions
<button onclick="onFileUpload()">
async onFileUpload () {
let response = await Neutralino.os.showDialogOpen({
title: 'Select a file'
})
console.log(`You've selected: ${response.selectedEntry}`)
}
Why do you need the path? If you need the content from the upload file you can get it via javascript filereader API and use the contents.
If you need the file for later use you can read the file via js filereader and then create and save a new file with filesystem.writeFile(WriteFileOptions) to your prefered location (maybe app internal temp path). Be sure the destination path exists. For that you can use filesystem.createDirectory(CreateDirectoryOptions).
Example with jQuery:
jQuery(document).on('change','#myUpload',function(){ //Click on file input
if(jQuery(this).val().length > 0){ //Check if a file was chosen
let input_file = this.files[0];
let file_name = input_file.name;
let fr = new FileReader();
fr.onload = function(e) {
fileCont = e.target.result;
//Do something with file content
saveMyFile(file_name, fileCont); //execute async function to save file
};
fr.readAsText(input_file);
}
});
async function saveMyFile(myFileName, myFileContent){
await Neutralino.filesystem.createDirectory({ path: './myDestPath' }).then(data => { console.log("Path created."); },() => { console.log("Path already exists."); }); //create path if it does not exist
//write the file:
await Neutralino.filesystem.writeFile({
fileName: './myDestPath/' + myFileName,
data: myFileContent
});
}
You can use the Neutralino.os API for showing the Open/Save File Dialogs.
This is A Example For Opening A File.
HTML:
<button type="button" id="inputFile">Open File</button>
JavaScript:
document.getElementById("inputFile").addEventListener("click", openFile);
async function openFile() {
let entries = await Neutralino.os.showOpenDialog('Save your diagram', {
filters: [
{name: 'Images', extensions: ['jpg', 'png']},
{name: 'All files', extensions: ['*']}
]
});
console.log('You have selected:', entries);
}
Related
I have written function where I want to download an xlsx file via a service. Download also works so far. But when I open the file I get the error message file extension or file format is invalid. How can I solve the problem?
Code:
// Service
getDownloadPlan(): Observable<any> {
const url = `/download-plan?sales-plan=0&personnel-plan=0&investment-plan=0&loan-plan=0&material-cost-plan=0`;
return this.http.get(`${environment.baseUrl}` + url, { responseType: 'blob'});
}
// TS
downloadPlanBwa() {
this.planBwaService.getDownloadPlan().subscribe(response => {
const downloadFile: any = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
fileSaver.saveAs(downloadFile, 'Plan');
}, error => console.log('ERROR'),
() => console.log('SUCCESSFUL')
);
}
If i use the MIME-Type application/vnd.ms-excel;charset=utf-8 this is for the xls-format then it works.
What do I need to change in my code to successfully open xlsx files?
I am trying to read from a excel file, manipulate and create another excel file from it, i am using stream support for this. Most of it is working fine but i see resultant excel file containing {"sharedString":0} instead of actual values.
Below is my relevant code
let ws = fs.createWriteStream(fpath);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({stream: ws, useStyles: true, useSharedStrings: true});
const myworksheet = workbook.addWorksheet('sheet1');
const workbookReader = new ExcelJS.stream.xlsx.WorkbookReader(sheet.path, options);
workbookReader.read();
workbookReader.on('worksheet', worksheet => {
worksheet.on('row', row => {
myworksheet.addRow(row.values);
});
});
workbookReader.on('shared-strings', sharedString => {
console.log('not coming here');
});
workbookReader.on('end', async () => {
console.log('processing done...');
await workbook.commit();
});
Please see the attached file for your reference.
Any help on how to fix this will be really great, Thanks.
Once i created the WorkbookReader with below options
const options = {
sharedStrings: 'cache',
hyperlinks: 'cache',
worksheets: 'emit',
styles: 'cache',
};
it worked!
I am trying to upload images to realtime firebase database. I made it with one images but I have no idea how to add multiple images.
This is my solution for one image.
<v-layout row>
<v-flex xs12 sm6 offset-sm3>
<!-- accept nam govori da uzme slike i nista vise-->
<v-btn raised #click="onPickFile">Upload image</v-btn>
<input
type="file"
style="display:none"
ref="fileInput"
accept="image/*"
#change="onFilePicked"/></v-flex
></v-layout>
In data I have this two: imgURL: "",
image: null
And this is a method:
onFilePicked(event) {
//files is list of imaages by puting files[0] we are taking just one
const files = event.target.files;
let filename = files[0].name;
if (filename.lastIndexOf(".") <= 0) {
return alert("Please add a valid file!");
}
const fileReader = new FileReader();
fileReader.addEventListener("load", () => {
this.imgURL = fileReader.result;
});
fileReader.readAsDataURL(files[0]);
this.image = files[0];
},
Although, this is not a firebase related question, but I try to help anyway:
First of all, you should add multiple to the input-tag, so you can select more than only one file there:
// CHANGE THIS:
<input type="file" style="display:none" ref="fileInput" accept="image/*" #change="onFilePicked"/>
// TO THIS:
<input type="file" style="display:none" ref="fileInput" accept="image/*" #change="onFilePicked" multiple/>
I assume you stumbled upon this wierd 'for-loop' for the files.. I had the same issue and figured out when I type of instead of in, then I get the file itself, not just the index and there is no error.
I splitted up the main parts of your function and converted them in asyncron Promises (because there might be a timing error with the addEventListener)
This is just the idea of the multiple files upload. Maybe you should add some more error-catcher:
new Vue({
data: {
blobs: [],
images: [],
},
methods: {
async onFilePicked(event) {
const files = event.target.files
this.images =[]
this.blobs =[]
for (let file of files) {
this.images.push(file)
let blob = await this.prepareImagesForUpload(file)
this.blobs.push(blob)
}
this.uploadImagesToFirebase()
},
prepareImagesForUpload(file) {
return new Promise((resolve, reject) => {
let filename = file.name
if (filename.lastIndexOf(".") <= 0) {
alert("Please add a valid file: ", filename)
reject()
}
const fileReader = new FileReader()
fileReader.readAsDataURL(file)
fileReader.addEventListener("load", async () => {resolve(fileReader.result)})
})
},
uploadImagesToFirebase() {
//... do the firebase upload magic with:
console.log(this.blobs)
//...
}
}
})
I am trying to open a File Dialog Box with React, so that the user can select a folder and save the file in that particular folder, however I cannot manage to do that. My code looks like this at the moment:-
const exportToCSV = (csvData, fileName) => {
const ws = XLSX.utils.json_to_sheet(csvData);
const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] };
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const data = new Blob([excelBuffer], {type: fileType});
FileSaver.saveAs(data, fileName + fileExtension);
}
const openDialogWindow = () => {
// Open dialog here and get the folder name
exportToCSV(csvData, (folderName + fileName))
};
return (
<button
id="btnExportToCSV"
onClick={(e) => openDialogWindow()}
>
Export Tasks To Excel
</button>
)
so in my openDialogWindow, I would like to have the option to open the dialog box, and let the user select a folder that I can then attach to the pre-defined fileName. This will give the user the option to save the file in his chosen directory.
Is this possible?
Thanks for your help and time!
How can I upload my files to NetSuite file cabinet using SuiteScript 2.0?
A possible option is to create a Suitelet with a Document field and save the file uploaded to that field. Here's the code for such a Suitelet:
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(['N/ui/serverWidget'],
function(serverWidget) {
function onRequest(context) {
if (context.request.method === 'GET') {
var form = serverWidget.createForm({
title: 'Simple Form'
});
var field = form.addField({
id: 'custpage_file',
type: 'file',
label: 'Document'
});
form.addSubmitButton({
label: 'Submit Button'
});
context.response.writePage(form);
} else {
var fileObj = context.request.files.custpage_file;
fileObj.folder = 4601; //replace with own folder ID
var id = fileObj.save();
}
}
return {
onRequest: onRequest
};
});
I see you're talking about uploading files from local storage. You can create a file of specified type, based on the record you're working with in your script. By specifying a folder, this file can be saved, while also being available for further processing within your script.
I believe the below can be adapted to use your uploaded file by specifying the 'contents' as 'context.request.files.custpage_file' - as done in Maria's answer.
var exportFolder = '1254';
var recordAsJSON = JSON.stringify(scriptContext.newRecord);
var fileObj = file.create({
name: scriptContext.newRecord.id + '.json',
fileType: file.Type.JSON,
contents: recordAsJSON, description: 'My file', encoding: file.Encoding.UTF8,
folder: exportFolder,
isOnline: false
});
var fileId = fileObj.save();
fileObj.save() will return the internal ID of the newly created file in the file cabinet.