如何通过Web服务调用将文件保存到我的Node.js服务器

时间:2019-03-01 15:10:57

标签: node.js pdf fs

我的问题是这样的: 我已致电某人的Web服务。我得到了文件名,扩展名和“字节”。字节实际上是作为数组输入的,并且在位置0处“ Bytes [0]”是以下字符串:

submission = Submission.find(1)
submission.histories
# SubmissionFieldHistory Load (5.5ms)  SELECT "submission_field_histories".* FROM "submission_field_histories"
#   WHERE "submission_field_histories".is_deleted = false
#   AND /* A complex query */ LIMIT $1  [["LIMIT", 11]]

为便于阅读,上面的字符串示例已被截断。 如何获取该字符串并将其另存为可读文件? 这种情况是pdf。

JVBERi0xLjYKJeLjz9MKMSAwIG9iago8PC9EZWNvZGVQYXJtczw8L0sgLTEvQ29sdW1ucyAyNTUwL1Jvd3MgMzMwMD4+L1R5cGUvWE9iamVjdC9CaXRzUGVyQ29tcG9uZW50IDEvU3VidHlwZS9JbWFnZS9XaWR0aCAyNTUwL0NvbG9yU3BhY2UvRGV2aWNlR3JheS9GaWx0ZXIvQ0NJVFRGYXhEZWNvZGUvTGVuZ3RoIDI4Mzc0L0hlaWdodCAzMzAwPj5zdHJlYW0K////////y2IZ+M8+zOPM/HzLhzkT1NAjCCoEY0CMJNAjCR4c8HigRhBAi1iZ0eGth61tHhraTFbraRaYgQ8zMFyGyGM8ZQZDI8MjMI8M6enp9W6enp+sadIMIIEYwy/ggU0wwgwjWzSBUmwWOt/rY63fraTVNu6C7R7pN6+v///20v6I70vdBaPjptK8HUQfX9/17D/TMet+l06T//0v3/S9v+r98V0nH///7Ff+Ed3/v16X9XX/S/KP0vSb//W88ksdW18lzBEJVpPXT0k9b71///...

2 个答案:

答案 0 :(得分:2)

您可以使用Node.js文件系统模块来保存接收到的缓冲区。
假设您的数据编码为base64:

const fs = require('fs');

let pdfBytes = 'JVBERi0xLjYKJeLjz9...'

let writeStream = fs.createWriteStream('filename.pdf');

writeStream.write(pdfBytes, 'base64');

writeStream.on('finish', () => {  
    console.log('saved');
});

writeStream.end(); 

答案 1 :(得分:0)

我在这里使用fs文件系统来创建和保存文件。如果发生任何问题,我会进行大量尝试。此示例说明了如何将数据传递给可以为您创建文件的函数。

const util = require('util');
const fs = require('fs');

const fsOpen = util.promisify(fs.open);
const fsWriteFile = util.promisify(fs.writeFile);
const fsClose = util.promisify(fs.close);

function saveNewFile(path, data) {
  return new Promise((async (resolve, reject) => {
    let fileToCreate;

    // Open the file for writing
    try {
      fileToCreate = await fsOpen(path, 'wx');
    } catch (err) {
      reject('Could not create new file, it may already exist');
      return;
    }

    // Write the new data to the file
    try {
      await fsWriteFile(fileToCreate, data);
    } catch (err) {
      reject('Error writing to new file');
      return;
    }

    // Close the file
    try {
      await fsClose(fileToCreate);
    } catch (err) {
      reject('Error closing new file');
      return;
    }

    resolve('File created');
  }));
};

// Data we want to use to create the file.
let pdfBytes = 'JVBERi0xLjYKJeLj...'
saveNewFile('./filename.pdf', pdfBytes);