简体   繁体   English

蒸气中的文件处理

[英]file handling in vapor

I am wondering if there is a possibility to create file-handling code in Vapor ? 我想知道是否有可能在Vapor中创建文件处理代码? (Swift) (迅速)

For example, I want to create a folder on the server, then copy an existing file from one location on the server to this folder. 例如,我要在服务器上创建一个文件夹,然后将现有文件从服务器上的一个位置复制到此文件夹。

Is this possible in Vapor ? 蒸气中可能吗?

I did the file-copying in php as can be seen in the below function that actually copies a file from source to destination : 我在php进行了文件复制,如下面的函数所示,该函数实际上将文件从源复制到目标:

<?php
function copyr($source, $dest, $permissions = 0701)
{
    // Check for symlinks
    if (is_link($source)) {
        return symlink(readlink($source), $dest);
    }

    // Simple copy for a file
    if (is_file($source)) {
        copy($source, $dest);
        return chmod($dest, 0204);
    }

    // Make destination directory
    if (!is_dir($dest)) {
        mkdir($dest, $permissions);
    }

    // Loop through the folder
    $dir = dir($source);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }

        // Deep copy directories
        copyr("$source/$entry", "$dest/$entry", $permissions);
    }

    // Clean up
    $dir->close();
    return true;
}
?>

You can try this code, it may work in your case. 您可以尝试使用此代码,它可能适合您的情况。

Suppose I like to copy one file from my project to a new folder outside my project folder. 假设我想将一个文件从项目复制到项目文件夹之外的新文件夹。

// Get the project directory
let directory = DirectoryConfig.detect()
let filePath = directory.workDir + "../mydoc"

Now create the directory using FileManager . 现在使用FileManager创建目录。 It will create a folder outside your project folder. 它将在项目文件夹之外创建一个文件夹。

do {
   try FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
   } catch let error as NSError {
        print(error.localizedDescription);
   }

Now, get your absolute file path with extension that needs to be copied. 现在,获取需要复制的带有扩展名的绝对文件路径。

 let myfile = directory.workDir + "README.md"
 let destPath = directory.workDir + "../mydoc/README.md"

    do {
        try FileManager.default.copyItem(at: URL(fileURLWithPath: myfile), to: URL(fileURLWithPath: destPath))
        print("Copy success")
    } catch let error as NSError {
        print(error.localizedDescription);
    }

You will see the file is copied. 您将看到文件已复制。 This is working in my local PC. 这在我的本地PC上运行。 I can't grantee for the server due to the server security. 由于服务器的安全性,我无法为服务器授予权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM