set download button disabled on Generating an excel file - javascript

I'm generating an excel sheet using exceljs and downloading it using file-saver packages
const saveFile = async (fileName: any, workbook: any) => {
protectSheet(validationSheet)
const xls64 = await workbook.xlsx.writeBuffer({ base64: true })
saveAs(
new Blob([xls64], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
fileName
)
}
the problem is when I trigger this function by clicking this button
<button ref={buttonRef} className="btn btn-info" onClick={() => {
saveFile(fileName, workbook)
}}>Download file</button>
it takes some time to protect and generate the excel file.
i need to disable the button during the protection and generation phase
then enable it back after downloading

Related

how can i upload multiple files to s3 using nuxtjs

please I'm lost how can I upload multiple files
This is how I upload single files:
<div class="a-row a-spacing-top-medium">
<label class="choosefile-button">
<i class="fal fa-plus"></i>
<input
type="file"
#change="onFileSelected"
ref="files"
/>
<p style="margin-top: -70px">{{ fileName }}</p>
</label>
</div>
this is my script tag for image upload:
<script>
import axios from 'axios'
export default {
data() {
return {
selectedFile: null,
fileName: '',
photos: null
}
},
methods: {
onFileSelected(event) {
this.selectedFile = event.target.files[0]
console.log(this.selectedFile)
this.fileName = event.target.files[0].name
},
async onAddProduct() {
let data = new FormData()
data.append('photos', this.selectedFile, this.selectedFile.name)
const response = await axios
.post('http://localhost:5000/api/products', data)
.then(() => {
console.log(response)
})
}
}
}
</script>
each time I add multiple to my input tag it just uploads an image in my browser.
Please how can I go about multiple uploads?
Here's a basic blog post on how to upload a files to S3 in Vue through a node backend. This may help you out.
Basically what you need to do is create a backend that handles the files and uploads them. This can be done using multer, multer-s3 and node.
One thing that you should also change is just having
data.append('photos', this.selectedFile)
data.append('fileName', this.selectedFile.name)

Get input file path using NeutralinoJS

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);
}

Downloaded xlsx file with fileSaver is invalid when opened

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?

React Open file dialog

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!

React pdf onclick download

I have a problem with react. I have a program that embeds a pdf and a download button. I want to download the pdf upon clicking the button.
Instead, my program redirects me to another page where you download the pdf, meaning it exists in the app but I just want to stay in the same app and download the pdf in my app.
Are there any plugins that I can use to do this?
Please find below my code:
<div>
<object data={this.props.file} type='application/pdf'>
<embed src={this.props.file} type='application/pdf' />
</object>
{
this.props.author ==='bot' ?
<a href={this.props.file} download={this.props.file}>
<input alt='download' type={'image'} src={download} />
</a>
:
''
}
</div>
You can handle this with basic HTML. you do not need any plugins. I prefer using reactstrap instead of bootstrap.
import { Row, Col } from "reactstrap";
<Row>
{/* off set will middle the col */}
<Col md={{ size: 8, offset: 2 }}>
<div >
<a
//this will save the file as "your_cv.pdf"
download="your_cv.pdf"
//put the path of your pdf file
href="/static/resume.pdf"
//reactstrap classes. add green button
className="btn btn-success"
>
Download
</a>
</div>
<iframe
style={{ width: "100%", height: "800px" }}
src="/static/resume.pdf"
>
{" "}
</iframe>
</Col>
</Row>
You can download the pdf file as a blob and temporarily create a link to download that blob as a file. You can do something like:
fetch(this.props.file, {
method: 'GET',
headers: {...headers},
})
.then(res => res.blob())
.then(blob => {
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'YOUR_PDF_NAME.pdf');
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
});
Not sure how your pdf hosting server is configured, you can set the headers of request accordingly.
Try the following method using fetch call and save the file using FileReader object
fetch(this.props.file, {
method: "GET",
headers: {
Accept: "application/pdf",
"Content-Type": "application/pdf",
},
}).then(response => response.blob())
.then(response => {
var blob=response
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
window.open(base64data);
}
})
.catch(error => {
console.error(error);
});

Categories

Resources