Sam*_*her 6 node.js gridfs meteor server
我在服务器上使用GridFS存储Word(.docx)文件.我希望能够使用docx-builder NPM包将文档合并到一个Word文件中.
这是我上传文件的方式:
Meteor.methods({
uploadFiles: function (files) {
check(files, [Object]);
if (files.length < 1)
throw new Meteor.Error("invalid-files", "No files were uploaded");
var documentPaths = [];
_.each(files, function (file) {
ActivityFiles.insert(file, function (error, fileObj) {
if (error) {
console.log("Could not upload file");
} else {
documentPaths.push("/cfs/files/activities/" + fileObj._id);
}
});
});
return documentPaths;
}
})
Run Code Online (Sandbox Code Playgroud)
我怎样才能在服务器端执行此操作?我只能做这个服务器端因为我正在使用的fs包需要无法在客户端执行的包.
这就是我目前正在努力解决这个问题的方法.从客户端,我正在调用以下方法(声明为a Meteor.method):
print: function(programId) {
// Get the program by ID.
var program = Programs.findOne(programId);
// Create a new document.
var docx = new docxbuilder.Document();
// Go through all activities in the program.
program.activityIds.forEach(function(activityId) {
// Create a temporary server side folder to store activity files.
const tempDir = fs.mkdtempSync('/tmp/');
// Get the activity by ID.
var activity = Activities.findOne(activityId);
// Get the document by ID.
var document = ActivityFiles.findOne(activity.documents.pop()._id);
// Declare file path to where file will be read.
const filePath = tempDir + sep + document.name();
// Create stream to write to path.
const fileStream = fs.createWriteStream(filePath);
// Read from document, write to file.
document.createReadStream().pipe(fileStream);
// Insert into final document when finished writinf to file.
fileStream.on('finish', () => {
docx.insertDocxSync(filePath);
// Delete file when operation is completed.
fs.unlinkSync(filePath);
});
});
// Save the merged document.
docx.save('/tmp' + sep + 'output.docx', function (error) {
if (error) {
console.log(error);
}
// Insert into Collection so client can access merged document.
Fiber = Npm.require('fibers');
Fiber(function() {
ProgramFiles.insert('/tmp' + sep + 'output.docx');
}).run();
});
}
Run Code Online (Sandbox Code Playgroud)
但是,当我从ProgramFiles客户端的集合中下载最终文档时,该文档是一个空的Word文档.
这里出了什么问题?
我已将@ FrederickStark的答案纳入我的代码中.现在就坚持这一部分.
这是另一个尝试:
'click .merge-icon': (e) => {
var programId = Router.current().url.split('/').pop();
var programObj = Programs.findOne(programId);
var insertedDocuments = [];
programObj.activityIds.forEach(function(activityId) {
var activityObj = Activities.findOne(activityId);
var documentObj = ActivityFiles.findOne(activityObj.documents.pop()._id);
JSZipUtils.getBinaryContent(documentObj.url(), callback);
function callback(error, content) {
var zip = new JSZip(content);
var doc = new Docxtemplater().loadZip(zip);
var xml = zip.files[doc.fileTypeConfig.textPath].asText();
xml = xml.substring(xml.indexOf("<w:body>") + 8);
xml = xml.substring(0, xml.indexOf("</w:body>"));
xml = xml.substring(0, xml.indexOf("<w:sectPr"));
insertedDocuments.push(xml);
}
});
JSZipUtils.getBinaryContent('/assets/template.docx', callback);
function callback(error, content) {
var zip = new JSZip(content);
var doc = new Docxtemplater().loadZip(zip);
console.log(doc);
setData(doc);
}
function setData(doc) {
doc.setData({
// Insert blank line between contents.
inserted_docs_formatted: insertedDocuments.join('<w:br/><w:br/>')
// The template file must use a `{@inserted_docs_formatted}` placeholder
// that will be replaced by the above value.
});
doc.render();
useResult(doc);
}
function useResult(doc) {
var out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
});
saveAs(out, 'output.docx');
}
Run Code Online (Sandbox Code Playgroud)
查看 的文档docx-builder,它仅支持从文件系统读取 docx 文件。调用的问题document.url()在于,它为您提供了一个可以通过 http 访问的 url,而不是文件系统上的路径。
因此,要使用 GridFS,您首先需要将文件写入临时文件夹,然后docx-builder才能读取它们。
import fs from 'fs';
import { sep } from 'path';
const tempDir = fs.mkdtempSync('/tmp/' + sep);
program.activityIds.forEach(function(activityId) {
var activity = Activities.findOne(activityId);
console.log(activity);
var document = ActivityFiles.findOne(activity.documents.pop()._id);
documents.push(document);
// Build a file path in the temp folder
const filePath = tempDir + sep + document.name();
// Write the document to the file system using streams
const fileStream = fs.createWriteStream(filePath);
document.createReadStream().pipe(fileStream);
// When the stream has finished writing the file, add it to your docx
fileStream.on('finish', () => {
console.log(filePath);
docx.insertDocxSync(filePath);
// Delete the file after you're done
fs.unlinkSync(filePath);
});
});
Run Code Online (Sandbox Code Playgroud)
我怀疑您可以使用同步执行此操作fs.writeFileSync(filePath, document.data),但不确定,因此没有在示例中使用它。
或者,您可以查找可以支持从流或缓冲区读取的 docx 包,然后就不需要临时文件。
| 归档时间: |
|
| 查看次数: |
618 次 |
| 最近记录: |