It is possible to validate within a multiple Input file that one of the files is of type word (.doc, .docx) and another of type PDF (.pdf)?
I have a created a working codepen that shows you a javascript code which iterates over the files uploaded with the file upload input, and checks if their file extension is in pdf, doc or docx.
Though as others have mentioned in comments, checking file format in client-side is unsafe and you should double check on the server side.
Snippet below
function testFiles(){
var fileInput = document.getElementById('upload');
// iterate over files
for (let i = 0; i < fileInput.files.length; i++) {
var filename = fileInput.files[i].name
// get file extension
var file_extension = filename.split('.').pop()
if(file_extension == "pdf"
|| file_extension == "doc"
|| file_extension == "docx"){
alert(filename + ' is a .pdf, .doc or .docx file')
}
else alert(filename + ' is not an authorized file')
}
}
<input id="upload" type="file" onchange="testFiles()" multiple>
We have an issue tracking system on our intranet where we need to add effected files to the issue, including the path of the file.
We have been using an asp.net FileUpload control and using FileUpload1.PostedFile.FileName to get the path of the file that the user selects and uploads. The files are usually not on the users local machine, but on network drives that are on a separate server than the issue tracking system. We use the upload as an easy way to add files to the issue tracker.
This does not work in any recent browsers for security reasons, only on Internet Explorer which is on its way out.
Is there any way to get this to work? At least for intranet sites? Or is there a better way to go about this? We do absolutely need the file path, and if we had to copy and paste it would make this process take much longer as it would make it a two step process and many files often need to be added.
Here is a snippet of the asp.net page:
<asp:FileUpload ID="FileUpload1" runat="server" />
And here is how I was getting the file path:
Dim sFileLocation As String = ""
Dim sFileName As String = ""
Dim sExtension As String = ""
sFileName = GetFileName(Me.FileUpload1.FileName)
sExtension = GetExtension(Me.FileUpload1.FileName)
sFileLocation = Me.FileUpload1.PostedFile.FileName
sFileLocation = sFileLocation.Replace(sFileName, "")
This is only works for IE 11, did not test IE edge.
Chrome does not work.
Due to intranet, we only allow use IE internally.
Here is the logic I am using to check the file size and name, validateFile function can get the file path without problem
<asp:FileUpload ID="fuAFS" runat="server" CssClass="cssAFS cssFu" AllowMultiple="false" Width="550px" /> <asp:Button ID="btnAFS" runat="server" Text="Upload AFS" OnClientClick="return ValidateFile('cssAFS');" />
function ValidateFile(cssName) {
var fu = $('.' + cssName);
//Empty upload control file.length == 1
if (fu.length > 0) { //Upload control exists
var pathName = fu.val();
if (pathName == '') {
alert('Missing file. Please click the Browse button to select a file with extension pdf.');
return false;
}
}
return true;
}
$('.cssFu').on('change', function (e) {
var maxFileSize = $('#<%=hdnMaxFileSize.ClientID%>').val();
if (e.target.files.length == 1) {
if (e.target.files[0] != null) {
var size = e.target.files[0].size; //IE
var fileSize = e.target.files[0].fileSize; //Firefox
var pathName = $(this).val();
var ext = pathName.substring(pathName.lastIndexOf(".") + 1, pathName.length).toLowerCase();
if (size > maxFileSize * 1024 * 1024 || fileSize > maxFileSize * 1024 * 1024) {
alert('File size exceeds limit. Maximum file size permitted is ' + maxFileSize + ' MB.');
$(this).val('');
// Prevent form Upload
e.stopPropagation();
e.preventDefault();
} else if (ext != 'pdf') {
alert('Invalid File. Please upload a File with extension: PDF');
$(this).val('');
// Prevent form Upload
e.stopPropagation();
e.preventDefault();
}
var fileName = pathName.substring(pathName.lastIndexOf("\\") + 1, pathName.length);
if (fileName != '' && fileName.length > 100) {
alert('File name length over 100 characters, please rename the file and upload again.');
$(this).val('');
// Prevent form Upload
e.stopPropagation();
e.preventDefault();
}
}
}
#rgorr - FileUpload will never give you the full path for security reasons.
Server.MapPath(FileUpload1.FileName);
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();
}
I have a form where user can upload multiple images. I need a way to enable user to select one image from the images he just uploaded as his main picture before submitting the form.
I have loaded the previews using JavaScript file reader. I have tried to add a name via JavaScript to the image user has selected, so it can be accessed as a post element in the PHP script. But it is not working since it cannot be accessed as a file. I have spent 3 full days over this before posting this question. It'll be a huge help I anyone could tell me on how to approach this problem.
Following is the form :
<input type="file" name="files[]" multiple="true" id="file">
<div class="list"></div>
Javascript code for loading previews:
var imagesPreview = function(input, p) {
var id=1;
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img class="thumb" id="'+id+'">')).attr('src', event.target.result).appendTo(p);
id++;
}
reader.readAsDataURL(input.files[i]);
}
}
};
PHP code for uploading files:
$total = count($_FILES['files']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "gig_pics/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
move_uploaded_file($tmpFilePath, $newFilePath);
$file_sql = "INSERT INTO `gig_pics`(id,gig_id,pic) VALUES ('','$gid','$newFilePath')";
$file_res = mysqli_query($conn,$file_sql);
}
}
And after adding the name with jquery, I tried accessing the image as post
$main_img_path = $_POST['selectImage'];
$main_img_path = $_FILES['selectImage'];
But I could do anything.
I think your problem lies in the way you are selecting the specific file from the list of files:
$main_img_path = $_FILES['selectImage'];
I've not used PHP in a while, but in my opinion if you are already looping through the files on the server, why not check for the main image while looping? Something like this (assuming $_POST['selectImage'] contains the temp file name of the selected image):
$total = count($_FILES['files']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
if ($tmpFilePath === $_POST['selectImage']) {
// This is the selected image
}
//Setup our new file path
$newFilePath = "gig_pics/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
move_uploaded_file($tmpFilePath, $newFilePath);
$file_sql = "INSERT INTO `gig_pics`(id,gig_id,pic) VALUES ('','$gid','$newFilePath')";
$file_res = mysqli_query($conn,$file_sql);
}
}
Like I said, this depends on what $_POST['selectImage'] contains as I'm not sure what you are storing there.
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.