简体   繁体   中英

send PDF file using websocket node.js

I have the following server:

 var pvsio                   = require("./pvsprocess"),
        ws                      = require("ws"),
        util                    = require("util"),
        http                    = require("http"),
        fs                      = require("fs"),
        express                 = require("express"),
        webserver               = express(),
        procWrapper             = require("./processwrapper"),
        uploadDir               = "/public/uploads",
        host                    = "0.0.0.0",
        port                    = 8082,
        workspace               = __dirname + "/public",
        pvsioProcessMap         = {},//each client should get his own process
        httpServer              = http.createServer(webserver),
        baseProjectDir          = __dirname + "/public/projects/",
        PDFDocument             = require ("pdfkit");

    var p, clientid = 0, WebSocketServer = ws.Server;

...
var wsServer = new WebSocketServer({server: httpServer});
    wsServer.on("connection", function (socket) {
        var socketid =  clientid++;
        var functionMaps = createClientFunctionMaps();
        socket.on("message", function (m) {

Is possible send a pdf file to the client inside socket.on("message" .. function ? I can send message using send(), there is some function to send files?

Thanks

I would just send the pdf in binary.

fs.readFile(something.pdf,function(err,data){
    if(err){console.log(err)}
    ws.send(data,{binary:true});
}

And at the client side, I would create a blob and an object url from the received binary data. From this onward, you can pretty much do anything, says open the pdf file in a new window/tab.

conn.onmessage = function(e){
    pdfBlob = new Blob([e.data],{type:"application/pdf"});
    url = webkitURL.createObjectURL(pdfBlob);
    window.open(url);
}

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM