Coldfusion cfftp putfile переименование, когда файл существует - PullRequest
3 голосов
/ 01 августа 2020

При загрузке файла с помощью cfftp, как определить, существует ли уже файл, и переименовать его?

<cfftp
connection = "myConnection"
action = "putFile"
name = "uploadFile"
localFile = "C:\files\upload\some_file.txt"
remoteFile = "some_file.txt"
existing = "some_file.txt">

Тег cffile имеет атрибут makeunique, что делает процесс очень простым. Спасибо.

Обновлено 02.08.20:

Это мой cfm.

<cfif isDefined("Form.FileContents")>
    <cfset localFileDirectory="c:\localfiles" />
    
    <!--- If directory does not exist, create it --->
    <cfif Not DirectoryExists(localFileDirectory)>
        <cfdirectory action = "create" directory="#localFileDirectory#" />
    </cfif>
    
    <!--- Upload file to temp location --->
    <cffile action = "upload"
        fileField = "FileContents"
        destination = "#localFileDirectory#" 
         nameconflict="overwrite" 
         result="tempFile"> 
     
    <!--- Set the FTP file destination location (directory) --->
    <cfset destinationPath = "remotefiles/myFiles" />
    <!--- initialize attachment service --->
    <cfset attachmentService = new ais.applications.components.service.aisdocdbFtpService()/>
    <!--- upload file to ftp site --->
    <cfset uploadResults = attachmentService.doUpload(destinationPath,tempFile)/>
    
    <cfif uploadResults.Succeeded>
        success
    <cfelse>
        fail
    </cfif>
<cfelse>
    <form method="post" action=<cfoutput>#cgi.script_name#</cfoutput>
        name="uploadForm" enctype="multipart/form-data">
        <input name="FileContents" type="file">
        
        <input name="submit" type="submit" value="Upload File">
    </form>
</cfif>

Это FTP-сервис, который я использую ..

<cfcomponent>
    <cfproperty name="overwriteFiles" type="boolean" />
    <cfproperty name="createDirectories" type="boolean" />
    
    <cfset FTPProps = {server="myServer", port = "21", username="myUser", password="myPassword", stopOnError="yes"} >
    
    <!--- Constructor --->
    <cffunction name="init" access="public" output="false" returntype="ais.applications.components.service.aisdocdbFtpService" hint="constructor">
        <cfargument name="overwriteFiles" type="boolean" required="false" default="false">
        <cfargument name="createDirectories" type="boolean" required="false" default="true">
        <cfset this.overwriteFiles = arguments.overwriteFiles/>
        <cfset this.createDirectories = arguments.createDirectories/>
        <cfreturn this/>
    </cffunction>
    
    <!--- doUpload --->
    <cffunction name="doUpload" access="public" returntype="any" output="false">
        <cfargument name="destinationPath" type="string" required="true"/>
        <cfargument name="tempFile" type="any" required="true"/>
        
        <cfset var sourcePath = "#tempFile.serverDirectory#"/>
        
        <!--- FTP to AIS Doc DB --->
        <cftry>
            <!---Open the connection --->                       
            <cfftp  action="open" connection="myConnection" timeout="600" attributeCollection="#FTPProps#" />   
            
            <cfif this.createDirectories>
                <cfset folders = ListToArray(arguments.destinationPath, '/')/>
                <cfset var path = ''/>
                <cfloop array="#folders#" index="folder" >
                    <cfset path = path & folder & '/'/>
                    
                    <!--- Make Sure Directory Exsists --->
                    <cfftp action="existsdir" connection="myConnection" directory="#path#" result="directoryCheck"/>
                    
                    <cfif !directoryCheck.returnValue>
                        <cfftp action="createdir" connection="myConnection" directory="#path#" result="createDirectoryResult"/>
                    </cfif>
                </cfloop>
            </cfif>
                
            <!--- Upload File --->
            <cfftp action="putfile" connection="myConnection" localfile="#sourcePath#\#tempFile.serverFile#" remoteFile="#destinationPath#/#tempFile.clientfile#" failIfExists="#!this.overwriteFiles#" transfermode="auto" result="uploadResult"/>
            <cfcatch type="any" name="exception">
                <cfrethrow/>
            </cfcatch>
            <cffinally>
                <!--- Clean Up Temp Files --->
                <cffile action = "delete" file = "#sourcePath#\#tempFile.serverFile#">
                 <!---close the connection --->      
                <cfftp action="close" connection="myConnection">
            </cffinally>                           
        </cftry>
        
        <cfreturn uploadResult/>
    </cffunction>
</cfcomponent>

Я проверил, что файл успешно загружается на удаленный сервер. Когда я пытаюсь загрузить второй раз с тем же именем файла, он все равно говорит, что это удалось.

Спасибо.

1 Ответ

1 голос
/ 01 августа 2020

Ваш существующий код создаст логическую переменную с именем cfftp.succeeded. Вы можете делать все, что хотите, если эта переменная имеет значение false.

Или вы можете запустить команду cfftp action = "listDir". Это создаст объект запроса, включающий имя каждого элемента, включая, это каталог. Вы можете выполнить запрос, чтобы узнать, существует ли файл.

Редактирование начинается здесь

Прочитав комментарии, я подумал о другом варианте. Сделайте имя файла уникальным, добавив что-нибудь в конце имени файла. UUID будет работать все время. Дата и время с точностью до миллисекунды, скорее всего, также будут работать все время, если вам нужно что-то короче

OriginalName = 'abc.txt';
FileNamePart = ListFirst(OriginalName, '.');
NewName1 = FileNamePart & DateTimeFormat(now(), 'yyyymmddHHnnssl');
NewName2 = FileNamePart & CreateUUID();  // could replace the hyphens with empty strings here.
Extension = ListLast(OriginalName, '.');
NewName = NewName2 & '.' & Extension;  // could also use NewName1


writeoutput("filename is #FileNamePart#<hr>");
writeoutput("extension is #Extension#<hr>");
writeoutput("NewName1 is #NewName1#<hr>");
writeoutput("NewName2 is #NewName2#<hr>");
writeoutput("NewName is #NewName#<hr>");
...