【问题标题】:Copying/Moving image from one folder to another将图像从一个文件夹复制/移动到另一个文件夹
【发布时间】:2020-07-30 12:47:15
【问题描述】:

我正在开发一个 Angular 应用程序。我有两个图像,即 X.png 和 Y.png。我想将这些图像从我的资产文件夹复制到 C 盘 c:\users\images 中的一个文件夹中。目标路径也是我作为变量接收的。我该怎么做?我试图在节点中编写一个类似这样的函数。

function moveIMage(ImageStyle, destination) {
    const fs = require('fs');

// destination will be created or overwritten by default.
    fs.copyFile('src\assests\images\' + ImageStyle,  'destination');
}

图像样式的值可以是 X 或 Y,基于此我想选择图像并将其移动到目的地。上面的代码不起作用。我该怎么做?

【问题讨论】:

  • 您的 Angular 应用程序中的 javascript 代码在浏览器中运行,而不是在服务器上,因此代码无法复制文件或需要“fs”库。这项工作需要通过在服务器上运行的代码来完成。该示例代码是 node.js 代码 - 所以它必须是 node.js 应用程序的一部分(可能使用 express) - 您的 Angular 应用程序需要向 nodejs 应用程序发出某种类型的请求以触发该代码。跨度>
  • Angular 是一个客户端框架。这意味着它在浏览器上运行,您不应该期望从角度访问磁盘的 API。使用带有发送参数的 Api 服务来实现

标签: javascript angular angular6 angular7 angular8


【解决方案1】:

您缺少回调。重写你的函数如下

const fs = require('fs');// I prefer require statements outside of function

function moveIMage(ImageStyle, destination) {
    // destination will be created or overwritten by default.
    fs.copyFile('src\assests\images\' + ImageStyle,  destination, (err) => {
       if(err) throw err;
       console.log('copied image')
    });
}

这也会复制文件而不是删除原始文件,如果你想电影文件使用 fs.rename https://nodejs.org/api/fs.html#fs_fs_rename_oldpath_newpath_callback

【讨论】:

  • 复制时如何重命名图像?
  • 如果要在复制时重命名,只需更改目标文件路径名即可。 fs.copyFile('source.txt', 'destination.txt', (err) => { if (err) throw err; console.log('source.txt was copied to destination.txt'); });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多