Troubleshooting openDialog() Extendscript code - javascript

I'm trying to write an openDialog() extendscript code that filters the selectable file types to only csv files on a mac. I was directed to the code here which does what I'm asking:  Link
I've written mostly the same thing, and the panel opens and allows me to select a file, but for some reason the filter doesn't work.
Here's what I have written:
// target the active Premiere Pro project
var activeSequence = app.project.activeSequence;
// import the CSV file
var file = File.openDialog("Select a CSV file to import.", fileFilter);
if (file) {
file.open("r");
var data = file.read();
file.close();
}
//This is the filter used by the openDialog function
function fileFilter(file){
index = file.name.lastIndexOf(".");
ext = file.name.substring(index + 1);
if(ext == "xml" || ext == "XML"){
return true;
}
return false;
}
Can anyone see what the issue might be?

I just tried the code from the link and it works fine for me.
Here is my a bit shortened version of the same code:
var file = File.openDialog("Select a CSV file to import", fileFilter);
function fileFilter(file) {
if (!file instanceof Folder) return true;
if (file.name.split('.').pop().toLowerCase() == 'csv') return true;
return false;
}
Just in case, on Windows it works much simplier:
var file = File.openDialog("Select a CSV file to import.", "*.csv");

Related

Flask-wtf with trix-editor - How do I upload images

I'm using Flask with one of my wtforms TextAreaFields mapped to Trix-Editor. All works well except for images using the built toolbar attach button.
I'd like to save the images to a directory on the backend and have a link to it in the trix-editor text. I'm saving this to a database.
I can make this work by adding an <input type='file'/>in my template like so:
{{ form.description }}
<trix-editor input="description"></trix-editor>
<input type="file"/>
and the following javascript which I found somewhere as an example.
document.addEventListener('DOMContentLoaded', ()=> {
let contentEl = document.querySelector('[name="description"]');
let editorEl = document.querySelector('trix-editor');
document.querySelector('input[type=file]').addEventListener('change', ({ target })=> {
let reader = new FileReader();
reader.addEventListener('load', ()=> {
let image = document.createElement('img');
image.src = reader.result;
let tmp = document.createElement('div');
tmp.appendChild(image);
editorEl.editor.insertHTML(tmp.innerHTML);
target.value = '';
}, false);
reader.readAsDataURL(target.files[0]);
});
// document.querySelector('[role="dump"]').addEventListener('click', ()=> {
// document.querySelector('textarea').value = contentEl.value;
// });
});
This saves the image embedded in the text. I don't want that because large images will take up a lot of space in the database and slow down loading of the editor when I load this data back into it from the database.
It is also ugly having the extra button when Trix has an attachment button in it's toolbar. So, I'd like to be able to click the toolbar button and have it upload or if that is too hard, have the built in toolbar button save the image embedded.
To save the images to a folder instead of embedded, the Trix-editor website says to use this javascript https://trix-editor.org/js/attachments.js
In this javascript I have to provide a HOST so I use
var HOST = "http://localhost:5000/upload/"
and I set up a route in my flask file:
#tickets.post('/_upload/')
def upload():
path = current_app.config['UPLOAD_DIRECTORY']
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
session["id"] = filename
file.save(os.path.join(path, filename))
return send_from_directory(path, filename)
I can select an image and it shows in the editor and it uploads to the directory on my backend as expected. But when I save the form the location of the image is not in in the document text (should be in there as something like <img src="uploads/image.png>
On the python console I see
"POST /_upload/ HTTP/1.1" 404 -
I can make this go away if I change the return on my route to something like return "200" But all the examples I have seen about uploading files have this or a render_template. I don't want to render a template so I'm using this although I don't really understand what it does.
I'm assuming I need to return something the javasript can use to embed the image link in the document. But I'm a total newbie (like you didn't figure that out already) so I don't know what to do for the return statement (assuming this is where the problem lies).
If anyone else is trying to figure this out this is what I ended up doing.
Still needs a but of tweaking but works.
First I modified the example javascript for uploading to use Fetch instead of XMLHttpRequest
const editor = document.querySelector('trix-editor');
(function() {
HOST = '/_upload/'
addEventListener("trix-attachment-add", function(event) {
if (event.attachment.file) {
uploadFileAttachment(event.attachment)
}
// get rid of the progress bar as Fetch does not support progress yet
// this code originally used XMLHttpRequest instead of Fetch
event.attachment.setUploadProgress(100)
})
function uploadFileAttachment(attachment) {
uploadFile(attachment.file, setAttributes)
function setAttributes(attributes) {
attachment.setAttributes(attributes)
alert(attributes)
}
}
function uploadFile(file, successCallback) {
var key = createStorageKey(file)
var formData = createFormData(key, file)
fetch(HOST, {method: 'POST', body: formData}).then(function(response){
response.json().then(function(data){
alert(data.file, data.status)
if (data.status == 204) {
var attributes = {
url: HOST + key,
href: HOST + key + "?content-disposition=attachment"
}
console.log(attributes)
successCallback(attributes)
}
})
})
}
function createStorageKey(file) {
var date = new Date()
var day = date.toISOString().slice(0,10)
var name = date.getTime() + "-" + file.name
return [day, name ].join("/")
}
function createFormData(key, file) {
var data = new FormData()
data.append("key", key)
data.append("Content-Type", file.type)
data.append("file", file)
return data
}
})();
Then modified my Flask route (which I'll refactor, this was just slapped together to make it work):
def upload():
path = current_app.config['UPLOAD_DIRECTORY']
new_path = request.form["key"].split('/')[0]
file_upload_name = os.path.join(path, request.form["key"])
print(file_upload_name)
upload_path = os.path.join(path, new_path)
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
if not os.path.exists(upload_path):
os.mkdir(upload_path)
filename = secure_filename(file.filename)
session["id"] = filename
attachment = os.path.join(upload_path, filename)
file.save(attachment)
file.close()
os.rename(attachment, file_upload_name)
print(os.listdir(upload_path))
return jsonify({'file': attachment, 'status': 204})
return f'Nothing to see here'
Anyway, I hope that helps as it took me ages to figure out.

JS FileReader: Read Excel and CSV from Local File and display on a table

I am allowing a user to upload a CSV or Excel file. I want to allow them to view the contents of the file upload before submitting it.
The upload works well but the display fails for Excel files.
It works for CSV files but I am unable to view the contents of Excel files here. Outputs some texts.
var lines = [];
$("#import_file").change(function(e) {
var ext = $("input#import_file").val().split(".").pop().toLowerCase();
if ($.inArray(ext, ["csv", "xlsx", "xls"]) == -1) {
alert("Please upload a valid CSV or Excel file.");
return false;
}
if (e.target.files != undefined) {
var reader = new FileReader();
reader.onload = function(e) {
lines = e.target.result.split('\r\n');
$('#contactsAlert').css('display', 'block');
$('#contactsAlert').text('Confirm the sample contacts are OK');
for (i = 0; i < lines.length; ++i) {
if (i === 11) {
break;
}
$('tableHtml').append('<table style="width:100%"><tr><th></th></tr><tr> <td>' + lines[
i] + '</td></tr></table>');
}
};
reader.readAsText(e.target.files.item(0));
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" required accept=".xlsx, .xls, .csv" name="import_file" id="import_file">
<span id="contactsAlert"></span>
<tableHtml />
Will someone let me know what am missing? You can test with any sample Excel or CSV file.
Thanks.
You may use SheetJS. It can read and handle spreadsheet files (.csv, .ods, xlsx, ...) in browser.
SheetJS has a demo which load and display spreadsheet files.

How to add a file extension to file without any

so I've downloaded a few blank HTML files with no file extensions.
(I know these are HTML because if I manually add .HTML to the end and open the file, / the file contains html elements.... like etc.)
So they're located in my downloads folder. I'm simply trying to add a file extension to each of these files in the dir folder "download".
Here's my code:
var fs = require('fs');
var files = fs.readdirSync('C:/Users/Nikki/Downloads').forEach(file => {
console.log(file);
//There is a file named "desktop.ini", skip this file.
if (file === "desktop.ini") {
console.log("desktop file")
} else {
//not sure why it doesn't change the file extension. Maybe because there is none!?
var replaceExt = require('replace-ext');
var path = 'C:/Users/Nikki/Downloads/' + file;
var newPath = replaceExt(path, '.html');
console.log(newPath);
}
/*
fs.rename(file, file+'.html', () => {
console.log("\nFile Renamed!\n");
// doesnt work... either...
});
*/
});
How can I add the HTML file extension to each of these files?
If your file doesn't have a file extension, you can try the following code snippet :
var pos = file.lastIndexOf(".");
file = file.substr(0, pos < 0 ? file.length : pos) + ".html";

I would like to load a list of urls to a var in any browsers' dev console (JavaScript)

I have a .txt file on my hard drive containing lots of URLs structured like this:
http://url1.com/
http://url2.com/
.
.
.
I want to load them to a var in Firefox's/Chrome's/IE's dev console so that it would be a vector of strings. I plan to visit these pages with a for loop. How can this be done?
<script>
var urls = [
'http://url1.com/',
'http://url2.com/'
];
</script>
You can generate this snippet with code or just have your file export a global variable and then load it via tags.
You can read a file via JavaScript from the page. You cannot upload a file to the developer's console.
I then modified the code bellow a bit to help you further. I added a scrape function that will help you request each URL one at a time.
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
function scrape(urls) {
url = urls.shift()
$.get(function (url) {
// get the url data here
scrape(urls);
});
}
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
scrape(reader.result.split("\n"));
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Modified version of:
Read a local text file using Javascript
The only way di make your JavaScript aware of local files is to HTTP GET them.
So probably you have to put your file somewhere handy in the project folder and procees with an AJAX request.
var httpRequest;
function makeRequest() {
httpRequest = new XMLHttpRequest();
request.open("GET", "files/url.txt", false);
request.send(null);
saveArray(request.responseText);
}
var array = [];
saveArray(string){
array = string.split("\n")
}
You can get the contents of the file to show up in the Console with the below snippet.
var file="file://C:/FileName.txt";
function read(file)
{
var File = new XMLHttpRequest();
File.open("GET", file, false);
File.onreadystatechange = function ()
{
if(File.readyState === 4)
{
if(File.status === 200 || File.status == 0)
{
var Text = File.responseText;
console.log(Text);
}
}
}
File.send(null);
}
I found a simple but not very elegant workaround for the issue. I just copy and paste the list into a var definition. I don't have to do this often, so it is kind of okay.

Can't view uploaded PDF file in data browser

I uploaded a pdf file to parse and it is visible in the data browser, but when I try to view it it says failed to load. I believe that my upload code is correct because it works for .docx files but not .pdf. Any ideas? Here is my code
function uploadFile (uploadId,fileName){
var fileUploadControl = $("#fileUpload")[0];
if(fileUploadControl.files.length>0){
var file = fileUploadControl.files[0];
var parseFile = new Parse.File(fileName,file);
parseFile.save().then(function(){
console.log("nsucciess");
//file has been saved to parse
},function(error){
//file could not be read or saved
console.log("error");
});
//var currentUser = Parse.User.current();
//currentUser.set(fileName,parseFile);
var ProjectFile = Parse.Object.extend("ProjectFile");
var projectFile = new ProjectFile();
projectFile.set("file",parseFile);
projectFile.save(null,{
success:function(projectFile){
console.log("success");
}
});
alert("everything works");
}
else{
alert("oh no");
}
}
Just solved: you have to add https://docs.google.com/viewer?url= before the link provided by Parse.com. For example: var yourUploadedPdfLink = "http://files.parsetfss.com/56accfec-1956-xxxxxx-abe8-xxxxxx/tfss-a7076e9c-xxxx-45fe-a8e8-xxxxxxx-MYDOCUMENT.pdf" To read it: "https://docs.google.com/viewer?url=" + yourUploadedPdfLink
And it'll works. So, you can't read pdf files clicking on them from Parse.com dashboard (at the moment).

Categories