[英]file handling in vapor
我想知道是否有可能在Vapor中創建文件處理代碼? (迅速)
例如,我要在服務器上創建一個文件夾,然后將現有文件從服務器上的一個位置復制到此文件夾。
蒸氣中可能嗎?
我在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;
}
?>
您可以嘗試使用此代碼,它可能適合您的情況。
假設我想將一個文件從項目復制到項目文件夾之外的新文件夾。
// Get the project directory
let directory = DirectoryConfig.detect()
let filePath = directory.workDir + "../mydoc"
現在使用FileManager創建目錄。 它將在項目文件夾之外創建一個文件夾。
do {
try FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
現在,獲取需要復制的帶有擴展名的絕對文件路徑。
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);
}
您將看到文件已復制。 這在我的本地PC上運行。 由於服務器的安全性,我無法為服務器授予權限。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.