Remove Google Form Submitted File - javascript

WORKING CODE HERE: https://jsfiddle.net/nateomardavis/e0317gb6/
ORIGINAL QUESTION BELOW
How do I remove a form-submitted file from Drive itself?
I'm having trouble sorting out why a google form is submitting files to both my drive (not in a folder) but also into an auto-generated submission folder.
I've been able to move the renamed file to a new folder and delete the copy in the auto-generated submission folder. I cannot figure out how to remove the copy that's just listed in "Drive", not in any folder.
THE PROCESS (EDIT)
Let me try to explain the process more. I have a form that collects files. Google automatically makes a folder and sub-folders. I have successfully renamed the submitted files, moved them to a new folder, and deleted them from the Google-generated folder. However, a copy of the original, unchanged file is going to Google Drive, the root folder. Steps 1-3 (below) work as expected. Step 4 is where I'm running into issues.
The original file being uploaded to a form. Note the file name.
The Google-generated folder. The file is submitted this folder.
The renamed file in a new folder. The original file is deleted from the folder above.
The original file is now showing up in Drive, not in a folder but there. The name of this file is the same as the originally uploaded one. The one which went to the "passes" folder and was then deleted from that folder.
SNIPPET
//RENAME PASSES
if (itemResponses[f].getItem().getTitle() == "PASSES") {
var files = itemResponses[f].getResponse();
//Logger.log(files.length);
if (files.length > 0) {
for (var n in files) {
var dFile = DriveApp.getFileById(files[n]);
dFile.setName("LSS - " + year + " - " + teamName + " - " + "PASSES - " + today );
teamFolder.addFile(dFile); //MOVE SUBMITTED DOCUMENTS TO THAT FOLDER
passesFolder.removeFile(dFile); //REMOVE FROM SUBMISSION FOLDER
DriveApp.getRootFolder().removeFile(dFile) // (DOES NOT WORK) REMOVE FROM DRIVE FOLDER
DriveApp.removeFile(dFile) // (DOES NOT WORK) REMOVE FROM DRIVE FOLDER
}
}
FULL CODE
function getLastResponse() {
var form = FormApp.openById('ID');
var today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy hh:mm a");
var year = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "YYYY");
Logger.log(today);
var formResponses = form.getResponses();
//Logger.log(formResponses.length);
var formResponse = formResponses[formResponses.length-1];
var respondentEmail = formResponse.getRespondentEmail()
var itemResponses = formResponse.getItemResponses();
Logger.log(itemResponses.length);
var teamName = itemResponses[2].getResponse();
//Logger.log("team name: " + teamName);
//CHECK FOLDERS
var dropbox = "Lititz Summer Showcase Team Check In (File responses)";
var folder, folders = DriveApp.getFoldersByName(dropbox);
var teamBox = teamName;
var teamFolder, teamFolders = DriveApp.getFoldersByName(teamBox);
var passesFolder = DriveApp.getFolderById('ID');
var rosterFolder = DriveApp.getFolderById('ID');
var teamInfoFolder = DriveApp.getFolderById('ID');
var permissionToTravelFolder = DriveApp.getFolderById('ID');
if (folders.hasNext()) { //CHECK IF DRIVE HAS FOLDER FOR FORM
folder = folders.next();
} else { //IF NOT CREATE FOLDER
folder = DriveApp.createFolder(dropbox);
}
if (teamFolders.hasNext()) { //CHECK IF FOLDER FOR TEAM EXISTS
teamFolder = teamFolders.next();
} else { //IF NOT CREATE FOLDER
teamFolder = folder.createFolder(teamBox);
teamFolder.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.COMMENT);
}
for (var f = 0; f < itemResponses.length; f++) {
Logger.log(itemResponses[f].getItem().getType());
Logger.log(itemResponses[f].getItem().getTitle());
if (itemResponses[f].getItem().getType() == "FILE_UPLOAD") {
Logger.log("THERE IS A FILE UPLOAD");
//RENAME PASSES
if (itemResponses[f].getItem().getTitle() == "PASSES") {
var files = itemResponses[f].getResponse();
//Logger.log(files.length);
if (files.length > 0) {
for (var n in files) {
var dFile = DriveApp.getFileById(files[n]);
dFile.setName("LSS - " + year + " - " + teamName + " - " + "PASSES - " + today );
teamFolder.addFile(dFile); //MOVE SUBMITTED DOCUMENTS TO THAT FOLDER
passesFolder.removeFile(dFile); //REMOVE FROM SUBMISSION FOLDER
DriveApp.removeFile(dFile); // REMOVE FROM DRIVE FOLDER
}
}
//RENAME ROSTER
} else if (itemResponses[f].getItem().getTitle() == "ROSTER") {
var files = itemResponses[f].getResponse();
//Logger.log(files.length);
if (files.length > 0) {
for (var n in files) {
var dFile = DriveApp.getFileById(files[n]);
dFile.setName("LSS - " + year + " - " + teamName + " - " + "ROSTER - " + today );
teamFolder.addFile(dFile);
}
}
//RENAME TEAM INFO SHEET
} else if (itemResponses[f].getItem().getTitle() == "TEAM INFO SHEET") {
var files = itemResponses[f].getResponse();
//Logger.log(files.length);
if (files.length > 0) {
for (var n in files) {
var dFile = DriveApp.getFileById(files[n]);
dFile.setName("LSS - " + year + " - " + teamName + " - " + "TEAM INFO SHEET - " + today );
teamFolder.addFile(dFile);
}
}
//RENAME PERMISSION TO TRAVEL
} else if (itemResponses[f].getItem().getTitle() == "PERMISSION TO TRAVEL") {
var files = itemResponses[f].getResponse();
//Logger.log(files.length);
if (files.length > 0) {
for (var n in files) {
var dFile = DriveApp.getFileById(files[n]);
Logger.log(ownerEmail);
dFile.setName("LSS - " + year + " - " + teamName + " - " + "PERMISSION TO TRAVEL - " + today );
teamFolder.addFile(dFile);
}
}
}
}//END 'IF FILE UPLOAD'
}//END FOR LOOP
}//END FUNCTION

How about this answer?
Issue:
The flow of upload from Google Form is as follows.
When the file is uploaded in the Form, the file is created to root folder.
When the form is submitted, the file in the root folder is copied by renaming the filename to the folder created by the form.
In above case, the file in root folder is different from the file in the folder created by Google Form. By this, DriveApp.getRootFolder().removeFile(dFile) in your "SNIPPET" didn't work. This is the reason of your issue of script.
Workaround:
You want to delete the file remained in the root folder.
In order to delete the file created in the root folder, how about this workaround?
Unfortunately, the original filename cannot be retrieved from the form response. But the file which was copied to the folder created by the form has the filename of the format like {original filename} - ####.{extension}. In this workaround, the original filename is retrieved from this filename, and move the file to the trash using the retrieved original filename.
Sample script:
This sample script is run by the installable form submit trigger. So when the form was submitted, the script is run and the uploaded file is moved to the destination folder and the original file in the root folder is moved to the trash.
Before run the script:
In this sample script, it supposes that the script is the container-bound script of Google Form. Please be careful this.
After cope and paste the script to the script editor, please set the destination folder ID to the script.
please install the installable form submit trigger. If the trigger has already been installed, please remove it and install again.
Please upload and submit a file using Google Form. By this, the script is run.
Script:
function formsubmit(e) {
var destFolderId = "###"; // Destination folder ID
if (e) {
Utilities.sleep(3000); // This is required.
var destfolder = DriveApp.getFolderById(destFolderId);
var items = e.response.getItemResponses();
for (var i = 0; i < items.length; i++) {
if (items[i].getItem().getType() == "FILE_UPLOAD") {
var files = items[i].getResponse();
for (var j = 0; j < files.length; j++) {
var file = DriveApp.getFileById(files[j]);
var filename = file.getName();
// Move uploaded file to the destination folder.
var uploadedFile = DriveApp.getFileById(files[j]);
var sourcefolder = uploadedFile.getParents().next();
destfolder.addFile(file);
sourcefolder.removeFile(file);
// Retrieve original filename.
var p1 = filename.split(" - ");
var extension = p1[p1.length - 1];
p1.pop();
var name = p1.join(" - ");
var p2 = "";
if (extension.indexOf(".") > -1) {
p2 = "." + extension.split(".")[1];
}
var orgFilename = name + p2;
// Move uploaded file to the trash.
var orgFiles = DriveApp.getRootFolder().getFilesByName(orgFilename);
if (orgFiles.hasNext()) {
var orgFile = orgFiles.next();
orgFile.setTrashed(true);
}
}
}
}
} else {
throw new Error("This sample script is run by the installable form submit trigger.");
}
}
Note:
This is a simple sample script for explaining this workaround. So please modify this for your situation.
In my environment, it was found Utilities.sleep(3000) was required. When the file is uploaded and the file is copied, the installable form submit trigger is run. At this time, if Utilities.sleep(3000) is not used, the file is moved before copying file is completed. By this, an error occurs. So I used it.
But I'm not sure whether the wait time of 3 seconds is the best. So if in your environment, an error occurs, please modify this.
I think that when a large file is uploaded, this value might be required to be large. Or also I think that running the script by the time-driven trigger might be better.
In this sample script, I used the installable form submit trigger. And when the form is submitted, the original file in the root folder is moved to the trash.
But I think that you can also run the script by the time-driven trigger. In this case, you can retrieve the response items by opening the form. About this, please select for your situation.
References:
Installable Triggers
setTrashed(trashed)
sleep(milliseconds)

Related

Adding layer only to the last PSD file in script CS6 ver 13 Bug

I have code which makes copies of images from one folder to another folder into theirs respective PSDs. Each image with the same name is pasted as new layer into another PSD with the same name. Condition checking if names are matched is
if(fileListString.search(workingDocName) !== -1)
Everything worked fined, until I added condition which prevents adding images into wrong PSDs in previous if statement
globals.markupFileNotFound = false;
and later if condition is false
else {globals.markupFileNotFound = true;}
Previously there was bug which runed script and add last copy of matched image from source folder (markups locations), to all remaining PSDs in target folder (working locations)
For example we have 001.PSD, 002.PSD, 003.PSD and 001.JPG, 002.JPG.
Without additional new condition 003.PSD gets copy of image from 002.JPG. And any next PSD file gets it too.
So with new condition it comes out that only 002.PSD gets image 002.JPG. But previous 001.PSD do not, even when it has 001.JPG respectivly.
And needed conditions worked
if(fileListString.search(workingDocName) !== -1) = true
globals.markupFileNotFound = false;
So code below should work, but it's not
//Paste the markups onto the working document
if(globals.markupFileNotFound == false) {
//Create the blank layer
var blankLayer = openDoc.artLayers.add();
//Rename the layer to blank Layer
blankLayer.name = "markups";
//paste the markups onto the markups layer
workingDoc.paste();
}
What i know this code supposes to work in newer CC PS versions.
[Link to folder structure]
#target photoshop
globals = {};
main();
function main() {
//Create a dialog box to get the details of where the markups and the working are stored
var dialogPrefs = "dialog{statictext:StaticText{bounds:[10,10,240,27], text:'Set the folder location of the markups'}, " +
"markupsButton:Button{bounds:[10,80,190,101], text:'Markups location'}, " +
"statictext:StaticText{bounds:[130,10,390,27], text:'Set the folder location of the working files'}," +
"workingButton:Button{bounds:[205,80,390,101], text:'Working location'}, " +
"transferButton:Button{bounds:[205,120,390,141], text:'Transfer markups'}, " +
"cancelButton:Button{bounds:[205,160,390,181], text:'Cancel'}};"
var windowFileLocation = new Window(dialogPrefs, "Set file locations");
//This is the markup window button
windowFileLocation.markupsButton.onClick = function() {
globals.markupFolder = Folder.selectDialog("Select markup location");
}
//Store the location of the markup files
//This is the working window button
windowFileLocation.workingButton.onClick = function() {
globals.workingFolder = Folder.selectDialog("Select working folder location");
}
//Store the location of the markup files
//This is the transfer button
windowFileLocation.transferButton.onClick = function() {
//Compare both folders to find the files with the same names and transfer markups
//Check both locations to make sure that they are valid
if (globals.markupFolder === null){
alert("You have not selected the markups folder. Please select and try gain");
} else if (globals.workingFolder === null){
alert("You have not selected the working folder. Please select and try gain");
} else {
//Define and empty array to store the file names in
var workingFileNameArray = [];
//Get a list of all the iles in the working folder
var fileList = globals.workingFolder.getFiles();
for(var a = 0; a < fileList.length; a++) {
//check to see if hte fileList item is a file or folder
if(fileList[a] instanceof File) {
//Converting filename to a string
var fileListString = fileList[a].toString();
if(fileListString.match(/.(jpg|tif|psd|bmp|gif|png|ico)$/)) {
workingFileNameArray[a] = fileList[a];
//open the file in photoshop
var openDoc = open(workingFileNameArray[a]);
//Make a variable containg the active document
var workingDoc = app.activeDocument;
//get the name of the file and cut the extension
var workingDocName = ((workingDoc.name).toString()).slice(0, -4);
//getting the color profile of the working file
var targetProfile = workingDoc.colorProfileName;
//Start working markups
searchMarkups(workingDocName, targetProfile);
//Paste the markups onto the working document
if(globals.markupFileNotFound == false) {
//Create the blank layer
var blankLayer = openDoc.artLayers.add();
//Rename the layer to blank Layer
blankLayer.name = "markups";
//paste the markups onto the markups layer
workingDoc.paste();
}
//Save document
workingDoc.save();
//Close the document
workingDoc.close();
}
}
}
alert("All markups have been transferred");
windowFileLocation.close();
}
}
//Cancel button
windowFileLocation.show();
}
function searchMarkups(workingDocName, targetProfile) {
//This is a function that will find the markup files that match the working file
//Define an empty array to store the file names in
var workingFileNameArray = [];
//Define and empty array to store the file names in
var fileList = globals.markupFolder.getFiles();
for(var a = 0; a < fileList.length; a++){
//checck to see if the fileList item is a file or folder
if(fileList[a] instanceof File) {
//Converting filename to a string
var fileListString = fileList[a].toString();
if(fileListString.match(/.(jpg|tif|psd|bmp|gif|png|ico)$/)) {
//Check the name of the open working file against all of the files in the markups folder and find one that matches
if(fileListString.search(workingDocName) !== -1){
//open that file
var openDoc = open(fileList[a]);
//Convert the markup file to match the profile on the working
openDoc.convertProfile(targetProfile, Intent.RELATIVECOLORIMETRIC, true, true);
//Select the whole canvas
openDoc.selection.selectAll();
//Add a new blank layer to the file
var blankLayer = openDoc.artLayers.add();
//Rename the layer to blank Layer
blankLayer.name = "blankLayer";
//copy merge
openDoc.selection.copy(true);
//Remove the blank layer
openDoc.layers.getByName("blankLayer").remove();
globals.markupFileNotFound = false;
//close the document
openDoc.close(SaveOptions.DONOTSAVECHANGES);
} else {
globals.markupFileNotFound = true;
}
}
}
}
}
Thanks in advance.
Additional credits to code author jamesmcdonald3d.com
Try this code. Please let me know how it goes. I'm pretty sure that .toString() on a file is giving you a full path, so be careful that the names of yours folders don't contain the same characters as your file names. I think Photoshop's open() can accept a reference to a file but it might need a path instead ...
#target photoshop
globals = {};
main();
function main() {
//Create a dialog box to get the details of where the markups and the working are stored
var dialogPrefs = "dialog{statictext:StaticText{bounds:[10,10,240,27], text:'Set the folder location of the markups'}, " +
"markupsButton:Button{bounds:[10,80,190,101], text:'Markups location'}, " +
"statictext:StaticText{bounds:[130,10,390,27], text:'Set the folder location of the working files'}," +
"workingButton:Button{bounds:[205,80,390,101], text:'Working location'}, " +
"transferButton:Button{bounds:[205,120,390,141], text:'Transfer markups'}, " +
"cancelButton:Button{bounds:[205,160,390,181], text:'Cancel'}};"
var windowFileLocation = new Window(dialogPrefs, "Set file locations");
//This is the markup window button
windowFileLocation.markupsButton.onClick = function() {
globals.markupFolder = Folder.selectDialog("Select markup location");
}
//Store the location of the markup files
//This is the working window button
windowFileLocation.workingButton.onClick = function() {
globals.workingFolder = Folder.selectDialog("Select working folder location");
}
//Store the location of the markup files
//This is the transfer button
windowFileLocation.transferButton.onClick = function() {
//Compare both folders to find the files with the same names and transfer markups
//Check both locations to make sure that they are valid
if (globals.markupFolder === null){
alert("You have not selected the markups folder. Please select and try again");
} else if (globals.workingFolder === null){
alert("You have not selected the working folder. Please select and try again");
} else {
//Define an empty array to store the file names in
var workingFilesPaths = [];
//Get a list of all the files in the working folder
var workingFiles = globals.workingFolder.getFiles();
for(var a = 0; a < workingFiles.length; a++) {
//check to see if the workingFiles item is a file or folder
if(workingFiles[a] instanceof File) {
//Converting filename to a string
var workingFilePath = workingFiles[a].toString();
// if(fileListString.match(/.(jpg|tif|psd|bmp|gif|png|ico)$/)) {
if(workingFilePath.match(/.psd$/)) {
workingFilesPaths[a] = workingFilePath;
//open the file in photoshop
var openWorkingPSD = open(workingFiles[a]);
//Make a variable containg the active document
var workingPSD = app.activeDocument;
//get the name of the file and cut the extension
var workingPSDname = ((workingPSD.name).toString()).slice(0, -4);
//getting the color profile of the working file
var workingPSDcolorProfile = workingPSD.colorProfileName;
//Start working markups
transferMatchingMarkupsToWorkingPSD(workingPSD,workingPSDname, workingPSDcolorProfile);
}
}
}
alert("All markups have been transferred");
windowFileLocation.close();
}
}
//Cancel button
windowFileLocation.show();
}
function transferMatchingMarkupsToWorkingPSD(workingPSD,workingPSDname, workingPSDcolorProfile) {
//This is a function that will find the markup files that match the working file
//Define an empty array to store the file names in
var markupFilesPaths = [];
//Define and empty array to store the file names in
var markupFiles = globals.markupFolder.getFiles();
for(var a = 0; a < markupFiles.length; a++){
//checck to see if the fileList item is a file or folder
if(markupFiles[a] instanceof File) {
//Converting filename to a string
var markupFilePath = markupFiles[a].toString();
if(markupFilePath.match(/.(jpg|tif|psd|bmp|gif|png|ico)$/)) {
//Check the name of the open working PSD against all of the files in the markups folder and find those that match
if(markupFilePath.search(workingPSDname) !== -1){
//open that file
var openMarkupFile = open(markupFiles[a]);
//Convert the markup file to match the profile on the working
openMarkupFile.convertProfile(workingPSDcolorProfile, Intent.RELATIVECOLORIMETRIC, true, true);
//Select the whole canvas
openMarkupFile.selection.selectAll();
//copy merge
openMarkupFile.selection.copy(true);
//Create the blank layer in working PSD
activeDocument = workingPSD;
var workingPSDlayer = workingPSD.artLayers.add();
//Rename the layer
workingPSDlayer.name = "markups";
//paste the markups onto the markups layer
workingPSD.paste();
//close the markup file
openMarkupFile.close(SaveOptions.DONOTSAVECHANGES);
}
}
}
}
//Save document
workingPSD.save();
//Close the document
workingPSD.close();
}

Is it possible to add condition if folder with particular name exists already in PSD file?

My specs: CS6 64bit ver 13
I have in shortcut script which add copies of images markupFiles with the same names from one folder, to PSDs workingPSD with the same names into another folder.
It worked fine and I was glad with the outcome but I wanted to add all existing markup layers in each PSD into one folder called "markups".
To do that I need condition checking if folder with name "markups" markupFolder exists in workingPSD.
If it is true I add layer workingPSDlayer into folder previously added workingPSDFolder.
If it is false I just add layer workingPSDlayer into already existing "markup" folder markupFolder
So is there any possibility to add condition if certain PSD has certain folder?
In this example if workingPSDhas already any folder named "markup"
Unfortunately this statement doesn't work:
if(workingPSD.LayerSets.getByName("markups") === markupFolder)
In this context:
//Markups folder search outcome
var markupFolder = workingPSD.LayerSets.getByName("markups");
//Checking if folder markups already exists
if(workingPSD.LayerSets.getByName("markups") === markupFolder) {
//adding working PSD layer into folder
var workingPSDlayer = markupFolder.artLayers.add();
//If there is no markup folder yet
} else {
//Creating new markup folder
var workingPSDFolder = workingPSD.layerSets.add();
//Naming it
workingPSDFolder.name = "markups";
//Adding layer into it.
var workingPSDlayer = workingPSDFolder.artLayers.add();
[Link to folder structure]
the whole code:
#target photoshop
globals = {};
main();
function main() {
//Create a dialog box to get the details of where the markups and the working are stored
var dialogPrefs = "dialog{statictext:StaticText{bounds:[10,10,240,27], text:'Set the folder location of the markups'}, " +
"markupsButton:Button{bounds:[10,80,190,101], text:'Markups location'}, " +
"statictext:StaticText{bounds:[130,10,390,27], text:'Set the folder location of the working files'}," +
"workingButton:Button{bounds:[205,80,390,101], text:'Working location'}, " +
"transferButton:Button{bounds:[205,120,390,141], text:'Transfer markups'}, " +
"cancelButton:Button{bounds:[205,160,390,181], text:'Cancel'}};"
var windowFileLocation = new Window(dialogPrefs, "Set file locations");
//This is the markup window button
windowFileLocation.markupsButton.onClick = function() {
globals.markupFolder = Folder.selectDialog("Select markup location");
}
//Store the location of the markup files
//This is the working window button
windowFileLocation.workingButton.onClick = function() {
globals.workingFolder = Folder.selectDialog("Select working folder location");
}
//Store the location of the markup files
//This is the transfer button
windowFileLocation.transferButton.onClick = function() {
//Compare both folders to find the files with the same names and transfer markups
//Check both locations to make sure that they are valid
if (globals.markupFolder === null){
alert("You have not selected the markups folder. Please select and try again");
} else if (globals.workingFolder === null){
alert("You have not selected the working folder. Please select and try again");
} else {
//Define an empty array to store the file names in
var workingFilesPaths = [];
//Get a list of all the files in the working folder
var workingFiles = globals.workingFolder.getFiles();
for(var a = 0; a < workingFiles.length; a++) {
//check to see if the workingFiles item is a file or folder
if(workingFiles[a] instanceof File) {
//Converting filename to a string
var workingFilePath = workingFiles[a].toString();
// if(fileListString.match(/.(jpg|tif|psd|bmp|gif|png|ico)$/)) {
if(workingFilePath.match(/.psd$/)) {
workingFilesPaths[a] = workingFilePath;
//open the file in photoshop
var openWorkingPSD = open(workingFiles[a]);
//Make a variable containg the active document
var workingPSD = app.activeDocument;
//get the name of the file and cut the extension
var workingPSDname = ((workingPSD.name).toString()).slice(0, -4);
//getting the color profile of the working file
var workingPSDcolorProfile = workingPSD.colorProfileName;
//Start working markups
transferMatchingMarkupsToWorkingPSD(workingPSD,workingPSDname, workingPSDcolorProfile);
}
}
}
alert("All markups have been transferred");
windowFileLocation.close();
}
}
//Cancel button
windowFileLocation.show();
}
function transferMatchingMarkupsToWorkingPSD(workingPSD,workingPSDname, workingPSDcolorProfile) {
//This is a function that will find the markup files that match the working file
//Define an empty array to store the file names in
var markupFilesPaths = [];
//Define and empty array to store the file names in
var markupFiles = globals.markupFolder.getFiles();
for(var a = 0; a < markupFiles.length; a++){
//checck to see if the fileList item is a file or folder
if(markupFiles[a] instanceof File) {
//Converting filename to a string
var markupFilePath = markupFiles[a].toString();
if(markupFilePath.match(/.(jpg|tif|psd|bmp|gif|png)$/)) {
//Check the name of the open working PSD against all of the files in the markups folder and find those that match
if(markupFilePath.search(workingPSDname) !== -1){
//open that file
var openMarkupFile = open(markupFiles[a]);
//Convert the markup file to match the profile on the working
openMarkupFile.convertProfile(workingPSDcolorProfile, Intent.RELATIVECOLORIMETRIC, true, true);
//Adding layer to PSD file to anable coping when only background layer exists
if(markupFilePath.match(/.(psd)$/)) {openMarkupFile.artLayers.add();}
//Select the whole canvas
openMarkupFile.selection.selectAll();
//copy merge
openMarkupFile.selection.copy(true);
//Adding copy of markup image into working PSD
//Create the blank layer in working PSD
activeDocument = workingPSD;
//Markups folder search outcome
var markupFolder = workingPSD.LayerSets.getByName("markups");
//Checking if folder markups already exists
if(workingPSD.LayerSets.getByName("markups") === markupFolder) {
//adding working PSD layer into folder
var workingPSDlayer = markupFolder.artLayers.add();
//If there is no markup folder yet
} else {
//Creating new markup folder
var workingPSDFolder = workingPSD.layerSets.add();
//Naming it
workingPSDFolder.name = "markups";
//Adding layer into it.
var workingPSDlayer = workingPSDFolder.artLayers.add();
}
//Rename the layer
workingPSDlayer.name = "markups";
//paste the markups onto the markups layer
workingPSD.paste();
//close the markup file
openMarkupFile.close(SaveOptions.DONOTSAVECHANGES);
}
}
}
}
//Save document
workingPSD.save();
//Close the document
workingPSD.close();
}
Thanks in advance. Additional credits to code author jamesmcdonald3d.com
Ok I found solution. It is less elegant, but i works. I copied loop from //Adding markup layers into working PSD to get logic value if current working PSD has any corresponding markup files
var ifPSDHasMatchedMarkups = true;
When this value is truethen I run condition //Adding markups folder to working PSDto add folder called "markups"
The only problem is when you run script again you have no possibility to check if you have already in working PSD folder called "markups". You create new one each time.
#target photoshop
globals = {};
main();
function main() {
//Create a dialog box to get the details of where the markups and the working are stored
var dialogPrefs = "dialog{statictext:StaticText{bounds:[10,10,240,27], text:'Set the folder location of the markups'}, " +
"markupsButton:Button{bounds:[10,80,190,101], text:'Markups location'}, " +
"statictext:StaticText{bounds:[130,10,390,27], text:'Set the folder location of the working files'}," +
"workingButton:Button{bounds:[205,80,390,101], text:'Working location'}, " +
"transferButton:Button{bounds:[205,120,390,141], text:'Transfer markups'}, " +
"cancelButton:Button{bounds:[205,160,390,181], text:'Cancel'}};"
var windowFileLocation = new Window(dialogPrefs, "Set file locations");
//This is the markup window button
windowFileLocation.markupsButton.onClick = function() {
globals.markupFolder = Folder.selectDialog("Select markup location");
}
//Store the location of the markup files
//This is the working window button
windowFileLocation.workingButton.onClick = function() {
globals.workingFolder = Folder.selectDialog("Select working folder location");
}
//Store the location of the markup files
//This is the transfer button
windowFileLocation.transferButton.onClick = function() {
//Compare both folders to find the files with the same names and transfer markups
//Check both locations to make sure that they are valid
if (globals.markupFolder === null){
alert("You have not selected the markups folder. Please select and try again");
} else if (globals.workingFolder === null){
alert("You have not selected the working folder. Please select and try again");
} else {
//Define an empty array to store the file names in
var workingFilesPaths = [];
//Get a list of all the files in the working folder
var workingFiles = globals.workingFolder.getFiles();
for(var a = 0; a < workingFiles.length; a++) {
//check to see if the workingFiles item is a file or folder
if(workingFiles[a] instanceof File) {
//Converting filename to a string
var workingFilePath = workingFiles[a].toString();
// if(fileListString.match(/.(jpg|tif|psd|bmp|gif|png|ico)$/)) {
if(workingFilePath.match(/.psd$/)) {
workingFilesPaths[a] = workingFilePath;
//open the file in photoshop
var openWorkingPSD = open(workingFiles[a]);
//Make a variable containg the active document
var workingPSD = app.activeDocument;
//get the name of the file and cut the extension
var workingPSDname = ((workingPSD.name).toString()).slice(0, -4);
//getting the color profile of the working file
var workingPSDcolorProfile = workingPSD.colorProfileName;
//Start working markups
transferMatchingMarkupsToWorkingPSD(workingPSD,workingPSDname, workingPSDcolorProfile);
}
}
}
alert("All markups have been transferred");
windowFileLocation.close();
}
}
//Cancel button
windowFileLocation.show();
}
function transferMatchingMarkupsToWorkingPSD(workingPSD,workingPSDname, workingPSDcolorProfile) {
//This is a function that will find the markup files that match the working file
//Define an empty array to store the file names in
var markupFilesPaths = [];
///Defining condition for adding markups folder into working PSD
//Define and empty array to store the file names in
var markupFiles = globals.markupFolder.getFiles();
for(var a = 0; a < markupFiles.length; a++){
//check to see if the fileList item is a file or folder
if(markupFiles[a] instanceof File) {
//Converting filename to a string
var markupFilePath = markupFiles[a].toString();
if(markupFilePath.match(/.(jpg|tif|psd|bmp|gif|png)$/)) {
//Check the name of the open working PSD against all of the files in the markups folder and find those that match
if(markupFilePath.search(workingPSDname) !== -1){
var ifPSDHasMatchedMarkups = true;
}}}}
//Adding markups folder to working PSD
if(ifPSDHasMatchedMarkups === true) {
activeDocument = workingPSD;
var workingPSDFolder = workingPSD.layerSets.add();
workingPSDFolder.name = "markups";
}
//Adding markup layers into working PSD
for(var a = 0; a < markupFiles.length; a++){
//check to see if the fileList item is a file or folder
if(markupFiles[a] instanceof File) {
//Converting filename to a string
var markupFilePath = markupFiles[a].toString();
if(markupFilePath.match(/.(jpg|tif|psd|bmp|gif|png)$/)) {
//Check the name of the open working PSD against all of the files in the markups folder and find those that match
if(markupFilePath.search(workingPSDname) !== -1){
//open that file
var openMarkupFile = open(markupFiles[a]);
//Convert the markup file to match the profile on the working
openMarkupFile.convertProfile(workingPSDcolorProfile, Intent.RELATIVECOLORIMETRIC, true, true);
//Adding layer to PSD file to anable coping when only background layer exists
if(markupFilePath.match(/.(psd)$/)) {openMarkupFile.artLayers.add();}
//Select the whole canvas
openMarkupFile.selection.selectAll();
//copy merge
openMarkupFile.selection.copy(true);
//Create the blank layer in working PSD
activeDocument = workingPSD;
var workingPSDlayer = workingPSDFolder.artLayers.add();
//Rename the layer
workingPSDlayer.name = "markups";
//paste the markups onto the markups layer
workingPSD.paste();
//close the markup file
openMarkupFile.close(SaveOptions.DONOTSAVECHANGES);
}
}
}
}
//Save document
workingPSD.save();
//Close the document
workingPSD.close();
}

File attachment is not opening-Not Allowed Error

This is my first attempt to prepare a dynamic pdf form in livecycle designer es4. In this form, there is an option to add and view attachment. As I have little experience in javascript coding, I went to the adobe forum and found a very good example here. I have done some changes in original code to run in my form. I can attach file successfully with this code. But my problem is that when I want to open file attachment in Acrobat Pro XI, it is showing below error instead of opening the file. This error is showing independent of file attachment type (e.g. .doc, .jpg, .txt and .pdf file).error image. Here is screenshot of security of Acrobat Pro XIscreenshot 1 screenshot 2 and file linkhere.
Below code is written in the form-
//Code for add button
// Get Import Name
var cName = AttachName.rawValue;
// Test for empty value
if(!/^\s*$/.test(cName))
{// Do Import
try{
var bRtn = event.target.importDataObject(cName);
if(bRtn)
{
var cDesc = AttachDesc.rawValue;
if(!/^\s*$/.test(cName))
{
var oAtt = event.target.getDataObject(cName);
oAtt.description = cDesc;
}
app.alert("File Attachment Successfully Imported",3);
}
else
app.alert("Unable to import File Attachment",0);
}catch(e){
app.alert("An Error Occured while Importing the File Attachment:\n\n" + e);
}
}
else
app.alert("Attachment name must be non-empty");
//code for populating dropdown list
this.rawValue = null;
this.clearItems();
var a = event.target.dataObjects;
if (a !== null) {
for (var i = 0; i < a.length; i++) {
this.addItem(a[i].name);
}
}
//code for open attachment button
var cName = AttachNameSel.rawValue;
//var nAction = ExportAction.rawValue;
try{
event.target.exportDataObject({cName:cName, nLaunch:2});
} catch(e) {
app.alert("An Error Occured while Exporting the File Attachment: " + cName + "\n\n" + e);
}
Any help from anyone in the community would be greatly appreciated.
Thanks
Tony

How to save the file by giving the file name from grid row containing columns,name,date,device

I have a Grid view With Name time , device , Upload control columns , When i click upload in Grid view , files will be uploaded and saved in a folder, but i need to save the file with name_time_device..
How to do it any help??
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
//FileUploadData.tName = Request.QueryString["name"];
//string fname = context.Server.MapPath("~/FileUploads/") + FileUploadData.Name + "_" + FileUploadData.Id + "/" + DateTime.Now.ToString("ddMMyyyy") + "/" + FileUploadData.deviceID + "_" +
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
file.SaveAs(fname);
}
context.Response.ContentType = "application/x-zip-compressed";
context.Response.Write("File Uploaded Successfully!");
}
File uploading and saving i am doing in javascript. the file is zipped..and saving it in uploads folder, but it need to be saved with name_id_date_device.zip..
I am using a function In that function i am using ajax call , above code is my generic handler to save the files..
file saving is from function, here while saving only i need to pass id_name_device so which ever user clicks upload and upload files his file will be saved by his id_name_device.zip..
Help??
Can you please speicify you are having problem in getting name, time, device from gridview or you have issue with file saving with name "name_id_date_device.zip"?
if you problem is saving file with a specific name and you are ok to get name, time or device from gridview then you should change this:
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
TO
string fname = context.Server.MapPath("~/uploads/" + "name_id_date_device.zip");
in this way your file will be saved with this given name.
if you want to add your flag with file name just concat it with your filename when you are saving.
string fname = context.Server.MapPath("~/uploads/" + "what_flag_name_time" + file.FileName);
.and if you have anyother problem please be more specific. Thanks

how do I remove an item that is set to upload?

I have created an uploader using javascript and php. The problem is that I only want to allow specific file types. I have it letting the user know the file is not valid but I am not sure how to remove the file from being uploaded. Can anyone tell me how to remove the upload?
multiUploader.prototype._preview = function(data) {
this.items = data;
if (this.items.length > 0) {
var html = "";
var uId = "";
for (var i = 0; i < this.items.length; i++) {
uId = this.items[i].name._unique();
if (typeof this.items[i] != undefined) {
if (self._validate(this.items[i].type) <= 0) {
var errorClass = '<h3 class="text-danger">Invalid file format' + this.items[i].name + '</h3>'
jQuery(".errorContent").append(errorClass);
jQuery.remove(this.items[i]);
}
html += '<div class="dfiles" rel="' + uId + '"><h5>' + this.items[i].name + '</h5><div id="' + uId + '" class="progress" style="display:none;"></div></div>';
}
}
jQuery("#dragAndDropFiles").append(html);
}
}
This is not all of the code, just the function that displays my error message and also shows the uploaded file on the page. I tried it with jQuery.remove but it does not work. Any ideas are appreciated
what is a "file type"? I could send you a .php file that ends in .jpg, would you accept that? (I hope not!). Let the user upload the files with a warning that files X, Y, Z are not going to be accepted based on extension mismatch. Then actually test their content to see if the files are truly what their extension claims, because -and this part is important- your javascript in no way guarantees that what you're going to get is what you wrote your scripts to allow. Changing your script in my browser is a matter of opening my devtools and rewriting your script, then hitting ctrl-s. Now my browser will be running my code, not your code, and happily upload my files anyway.
Always, always, server-verify the user data.

Categories

Resources