I have a php script which opens a csv file, edits it, then saves it using 'file_put_contents'. The saved location is the same server directory which contains the script.
file_put_contents($destination,$string);
However, I want the user to have control over where the file is saved on their computer (ie. locally.) Preferably, using a dialogue pop-up on their browser.
How would this be achieved? Do I need to add header information to the php script? Thanks in advance.
CodePudding user response:
- To save file in local with popup of window you can use JS (Blob Object) for it :
// ajax get data from server ( you can push file to server for editting it and return)
// data return of php : return stream_get_contents($file);
$.ajax({
type: "post",
url: url,
data: {...},
success: function (data) {
let blob = new Blob([data], { type: 'application/csv;charset=utf-8;' });
handleSaveCsv(blob);
}
});
async function handleSaveCsv(blob){
if( window.showSaveFilePicker ) {
const handle = await showSaveFilePicker({
suggestedName: 'csvExportName.csv',
types: [{
description: 'csv file',
accept: {'application/csv': ['.csv']},
}],
});
const writable = await handle.createWritable();
await writable.write( blob );
writable.close();
}
else {
const saveCsv = document.createElement( "a" );
saveCsv.href = URL.createObjectURL( blob );
saveCsv.download= 'csvExportName.csv';
saveCsv.click();
setTimeout(() => URL.revokeObjectURL( saveCsv.href ), 6000 );
}
}
window.showSaveFilePicker
for opening popup window