Blueimp jquery file upload alternative file names cause the preview missing - jquery-file-upload

The client can preview before uploading but cannot see after uploding as the local language file name.
So I want to rename the filename before upload the image for it can preview before and after uploading.
reference the https://github.com/blueimp/jQuery-File-Upload/wiki/API
How to provide alternative file names:
The name property of File objects is read only, but an alternative name can be provided as uploadName property for each individual file:
$('#fileupload').fileupload({
add: function (e, data) {
var count = data.files.length;
var i;
for (i = 0; i < count; i++) {
data.files[i].uploadName =
Math.floor(Math.random() * 1000) + '_' + data.files[i].name;
}
data.submit();
}
});
When I use above js function the preview is good function when the image add and submit to server immediately~
But when I delete
data.submit();
as I want client to decide if upload or not before uploading.
the preview image function is missing!
and cannot upload any file.
Does any code can rename for the unicode filename (as the local language encoing filename cannot show on the preview function when it uploaded) before submit to the server?

jquery.fileupload.js
....
} else {
$.each(options.files, function (index, file) {
// This check allows the tests to run with
// dummy objects:
if (that._isInstanceOf('File', file) ||
that._isInstanceOf('Blob', file)) {
formData.append(
($.type(options.paramName) === 'array' &&
options.paramName[index]) || paramName,
file,
file.uploadName || file.name
);
}
});
}
}
change the last
file.uploadName || file.name
to
encodeURI(file.uploadName || file.name)
then can see the write decode in the back
fileName = URLDecoder.decode(fileDetail.getFileName(), "UTF-8");

Related

How to get the Multi Selected files from the File Explorer in an extension command

In package.json you can add a command to the File Explorer context menu.
In File Explorer you can select multiple files but my command only gets the last selected file URI as argument.
Can I get a list of all the selected files in the File Explorer?
You could look at my extension Find and Transform to see how I parse multiple files when an explorer context menu command is triggered. [There is some extra code in there because that command can be triggered by a keybinding or explorer/editor/tab menus so they have to be handled differently.]
let contextMenuCommandFile = vscode.commands.registerCommand('find-and-transform.searchInFile', async (...commandArgs) => {
let args = {};
if (commandArgs?.length === 1 && !(commandArgs[0] instanceof vscode.Uri)) { // if from keybinding
let argsArray = Object.entries(commandArgs[0]).filter(arg => {
return searchCommands.getKeys().includes(arg[0]);
});
Object.assign(args, Object.fromEntries(argsArray));
}
args.filesToInclude = await parseCommands.parseArgs(commandArgs, "file");
args.triggerSearch = true;
searchCommands.useSearchPanel(args);
});
context.subscriptions.push(contextMenuCommandFile);
You might be missing this async (...commandArgs) => { to get all available passed arguments into an array.
...commandArgs will be of length 1 if coming from a keybinding and length 2 if trigggered from the context menu no matter how many files were selected in the Explorer before right-clicking on one and choosing the command.
commandArgs[0] is the single file (i.e., the last file) on which I right-clicked.
commandsArgs[1] is itself an array of all the selected files in the explorer.
I then send that commandArgs array to be parsed (since I just need a comma-separated list of the files selected) to parseCommands.parseArgs() [okay, strangely-named function!).
The operative bit there is:
else if (commandArgs[1][0] instanceof vscode.Uri) { // explorer/context
for (const resource of commandArgs[1]) {
const thisResource = vscode.workspace.asRelativePath(resource.fsPath);
resources += `${ thisResource }, `;
}
resources = resources.substring(0, resources.length - 2); // strip ', ' off end
return resources;
}

How to allow users to upload files with Google Form without login?

Where can I find code and instruction on how to allow users to upload files with Google Form without login?
I searched all over here and couldn't find any information.
https://developers.google.com/apps-script/reference
Thanks in advance.
The user will be uploading the files to your drive. So, google needs to verify the user. If there is no verification, someone can fill your drive in no time.
It is for your safety to know who has uploaded, so, login is must.
There's a workaround, I'm in a hurry to write the code now, but if you're interested let me know and I'll edit later.
Basically, you set up a web app with apps script, then you setup a custom HTML form, you'll have to manually collect the file, convert is to base64 then json, then when you catch it in apps script you reverse the process and save it wherever you want in your drive.
Since the user will be executing the script as you, there's no verification required
/*
These functions basically go through a file array and reads the files first as binary string (in second function), then converts the files to base64 string (func 1) before stringifying the files (after putting their base64 content into an object with other metadata attached; mime, name e.t.c);
You pass this stringified object into the body part of fetch(request,{body:"stringified object goes here"})
see next code block for how to read in apps script and save the files to google drive
N.B. The body data will be available under doPost(e){e.postData.contents}
*/
async function bundleFilesForUpload(){
let filesDataObj = [];
let copy = {fileInfo:{"ogname":"","meme":""},fileData:""};
for(let i = 0 ; i < counters.localVar.counters.filesForUploadArr.length ; i++){
let tempObj = JSON.parse(JSON.stringify(copy));
let file = counters.localVar.counters.filesForUploadArr[i];
tempObj.fileInfo.ogname = file.name;
tempObj.fileInfo.meme = file.type;
tempObj.fileData = await readFile(file).then((file)=>{
file = btoa(file);
return file;
}).then((file)=>{
return file;
})
filesDataObj.push(tempObj);
}
return filesDataObj;
}
async function readFile (file){
const toBinaryString = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
let parsedFile = null;
parsedFile = await toBinaryString(file);
return parsedFile;
}
/*From doPost downward, we read the file Array convert the base64 to blob and make a file in google drive using the blob and metadata we have, you may also see some sheet code, I'm using sheet as db for this */
//in buit function doPost in Code.gs
doPost(e){
const myDataObj = JSON.parse(e.postData.contents);
mainFileFunc(myDataObj.params[0].dataObj.images);
//the actual object structure might look different from yours, console log around
}
function mainFileFunc(fileArr) {
let myArrObj = [{"madeit":"toFileF"}];
let copy = JSON.parse(JSON.stringify(myArrObj[0]));
//sheet.getRange("A1").setValue(JSON.stringify(fileArr.length));
for(let i=0 ; i < fileArr.length ; i++){
myArrObj.push(copy);
let blob = doFileStuff(fileArr[i].data,fileArr[i].info[0].mime,fileArr[i].id);
myArrObj[i] = uploadFileOne(blob,fileArr[i].id);
myArrObj[i].mime = fileArr[i].info[0].mime;
myArrObj[i].realName = fileArr[i].name;
// sheet.getRange("A"+(i+1)).setValue(myArrObj[i].name);
// sheet.getRange("B"+(i+1)).setValue(myArrObj[i].url);
// sheet.getRange("C"+(i+1)).setValue(myArrObj[i].mime);
// sheet.getRange("D"+(i+1)).setValue(myArrObj[i].size);
}
return myArrObj;
}
function doFileStuff(filedata,filetype,filename){
var data = Utilities.base64Decode(filedata, Utilities.Charset.UTF_8);
var blob = Utilities.newBlob(data,filetype,filename);
return blob;
}
function uploadFileOne(data,filename) {
let myObj = {}
myObj["name"] = "";
myObj["realName"] = "Story_Picture";
myObj["url"] = "";
myObj["mime"] = "";
myObj["size"] = "";
myObj["thumb"] = "nonety";
var folders = DriveApp.getFoldersByName("LadhaWeb");
while (folders.hasNext()) {
var folder = folders.next();
folder.createFile(data);
}
var files = DriveApp.getFilesByName(filename);
while (files.hasNext()) {
var file = files.next();
myObj.name = file.getName();
myObj.url = file.getUrl();
myObj.mime = file.getMimeType();
myObj.size = file.getSize();
}
return myObj;
}
You can view the full frontend code for this project here and the backend here.
Hope this helps someone.

Take all text files in a folder and combine then into 1

I'm trying to merge all my text files into one file.
The problem I am having is that the file names are based on data previously captured in my app. I don't know how to define my path to where the text files are, maybe. I keep getting a error, but the path to the files are correct.
What am I missing?
string filesread = System.AppDomain.CurrentDomain.BaseDirectory + #"\data\Customers\" + CustComboB.SelectedItem + #"\";
Directory.GetFiles(filesread);
using (var output = File.Create("allfiles.txt"))
{
foreach (var file in new[] { filesread })
{
using (var input = File.OpenRead(file))
{
input.CopyTo(output);
}
}
}
System.Diagnostics.Process.Start("allfiles.txt");
my error:
System.IO.DirectoryNotFoundException
HResult=0x80070003
Message=Could not find a part of the path 'C:\Users\simeo\source\repos\UpMarker\UpMarker\bin\Debug\data\Customers\13Dec2018\'.
I cant post a pic, but let me try and give some more details on my form.
I select a combobox item, this item is a directory. then I have a listbox that displays the files in my directory. I then have a button that executes my desires of combining the files. thanks
I finally got it working.
string path = #"data\Customers\" + CustComboB.SelectedItem;
string topath = #"data\Customers\";
string files = "*.txt";
string[] txtFiles;
txtFiles = Directory.GetFiles(path, files);
using (StreamWriter writer = new StreamWriter(topath + #"\allfiles.txt"))
{
for (int i = 0; i < txtFiles.Length; i++)
{
using (StreamReader reader = File.OpenText(txtFiles[i]))
{
writer.Write(reader.ReadToEnd());
}
}
System.Diagnostics.Process.Start(topath + #"\allfiles.txt");
}

How to create/enable bookmarks when converting word document to PDF using office js

I used getFileAsync() method to create pdf of the word document:
Office.context.document.getFileAsync(Office.FileType.Pdf,
function(result) {
if (result.status == "succeeded") {
var myFile = result.value;
var sliceCount = myFile.sliceCount;
app.showNotification("File size:" + myFile.size + " #Slices: " + sliceCount);
// Now, you can call getSliceAsync to download the files, as described in the previous code segment (compressed format).
myFile.closeAsync();
}
else {
app.showNotification("Error:", result.error.message);
}
}
);
For more details: https://dev.office.com/reference/add-ins/shared/document.getfileasync
But once the pdf gets created, it doesn't show up the bookmarks. (Need to enable it like we can in ms word when we convert word to pdf through it's options setting)
Do we have any way in office js methods for enabling bookmarks of word document for pdf ?

CSV File create in Google Apps

I have tried to Upload .csv file via API using Google Apps (Script).
I give the below property in part of API URL.
"ZOHO_FILE":file.csv
Is there any way to create .csv file in Google Apps Script ?
If possible, pls let us know, how can create .csv file in Google Apps ?
Sorry for my english :-(
You can use this to convert a data range:
function convertRangeToCsvFile(dataRange) {
try {
var data = dataRange.getValues();
var csvFile = undefined;
// Loop through the data in the range and build a string with the CSV data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// Join each row's columns
// Add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
or this to download a whole sheet
function downloadSpreadsheet(){
//This function generates a pdf of your current spreadsheet and emails it to yourself as attachment
//Make sure your spreadsheet is not too big. The pdf size tends to be 200kb/page and if too large
//if the pdf is too large the urlFetch might timeout
var AUTH_TOKEN = "xxxxxxxxxxxxxx"; //Enter your AUTH_TOKEN
//You can receive it from https://appscripts.appspot.com/getAuthToken
var ssID=SpreadsheetApp.getActiveSpreadsheet().getId()+"&gid="+SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="
+ ssID + "&exportFormat=csv";
//Add &gid=x at the end of above url if you only want a particular sheet
//gid of a sheet can be obtained by the undocumented function getSheetId()
//ex: SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
//exportFormat=xls did not work when I tried. I dont know why
var auth = "AuthSub token=\"" + AUTH_TOKEN + "\"";
var res = UrlFetchApp.fetch(url, {headers: {Authorization: auth}});
var content=res.getContentText();
return content
}
You asked for Apps Script, I hope;
Section 2 and 3 of the article below tells how to import and export CSV
https://developers.google.com/apps-script/articles/docslist_tutorial#section2