我已经通过API搜索了这个,但我似乎无法找到我需要的东西。看一下mongo驱动程序API,看起来我需要使用GridFSBucket和流方法。但是,显示的所有示例都会传递文件名以启动上载过程。我的问题是如何处理,存储和检索通过输入类型="文件'上传的文件。形成?最好,我想存储缓冲区或类型数组,以便我可以在检索时轻松显示它,但如果不可能,我可以解决这个问题。
我的应用程序的目标是上传PDF文件,并使用PDFJS在画布中渲染它们。这是我到目前为止的代码:
HTML
<html>
<head>
<title> Test File </title>
</head>
<body>
<input type ="file" id = "pdf_file" value = "Upload" />
<input type ="submit" id = "submit" value = "Submit" />
<div id="canvases" style ="position:relative;">
<canvas id="layer" style = "z-index: 2;
position:absolute;
left:0px; top:0px; background-color: #00ff00; opacity:0.1"></canvas>
<canvas id ="pdf-canvas" style=" z-index: 1; position:absolute;
left:0px; top:0px; border:1px solid #000000;"></canvas>
</div>
<script src="test_annotate.js"></script>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
</body>
</html>
test_annotate.js
document.getElementById("submit").onclick = function() {
var file =document.getElementById("pdf_file").files[0];
console.log("new file!");
//Step 2: Read the file using file reader
var fileReader = new FileReader();
fileReader.onload = function() {
//Step 4:turn array buffer into typed array
var typedarray = new Uint8Array(this.result);
//Step 5:PDFJS should be able to read this
PDFJS.getDocument(typedarray).then(function(pdf) {
// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function(page) {
console.log('Page loaded');
var scale = 1.3;
var viewport = page.getViewport(scale);
// Prepare canvas using PDF page dimensions
var canvas = document.getElementById('pdf-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.then(function () {
//set the annotation canvas size to match the size of the pdf
var canvas_container = document.getElementById('canvases');
canvas_container.style.height = renderContext.viewport.height;
canvas_container.style.width = renderContext.viewport.width;
var layer = document.getElementById('layer');
layer.height = renderContext.viewport.height;
layer.width = renderContext.viewport.width;
});
});
});
};
//Step 3:Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);
}
App.js
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var mongodb = require('mongodb');
var app = express();
app.use(bodyParser.json());
app.use(express.static('frontend'))
var MongoClient = mongodb.MongoClient;
//Grid = mongodb.Grid;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
if(err) return console.dir(err);
var bucket = new mongodb.GridFSBucket(db);
/*What do I do here to store the uploaded file in test_annotate.js
using mongoDB and GridFS??? */
});