我如何完全复制一个文件并更改其名称?

3

我需要生成上传的图像文件的缩略图,并在每个文件名后面添加“_preview”。

目前我正在这样做:

uploadFile.map((file) => {
      if (file.type.includes('image')) {
        console.log('Generating thumbnail for ' + file.name)
        const fileName = file.name.split('.').slice(0, -1).join('.')
        const fileExtension = file.name.split('.').pop()
        const compressedFile = new File(
          [file.slice(0, file.size, file.type)],
          fileName + '_preview.' + fileExtension,
        )
        console.log('Generated file:', compressedFile)
        convert({
          file: compressedFile,
          width: 300,
          height: 300,
          type: fileExtension,
        })
          .then((resp) => {
            uploadFile.push(resp)
          })
          .catch((error) => {
            // Error
            console.error('Error compressing ', file.name, '-', error)
          })
      }
    })

问题在于“compressedFile”缺少原始文件中存在的一些字段,因此转换函数会抛出错误“不支持的文件类型”。您可以看到,“type”和“webkitRelativePath”未被复制。

enter image description here

有人能建议我如何保留原始文件的所有信息,只需在文件名末尾添加“_preview”?

2个回答

0

-2

如果需要在JS中复制代码或者进行复制操作,您可以使用以下代码:


    //copyfile.js
    const fs = require('fs');
    
    // destination will be created or overwritten by default.
    fs.copyFile('C:\folderA\myfile.txt', 'C:\folderB\myfile.txt', (err) => {
      if (err) throw err;
      console.log('File was copied to destination');
    });


这不是我要问的。 - Ashar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接