如何在javascript中打开图像,由express.js sendfile函数发送[+解决方案] [英] How to open image in javascript,sent by express.js sendfile function[+SOLUTION]

查看:109
本文介绍了如何在javascript中打开图像,由express.js sendfile函数发送[+解决方案]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的服务器,有这个方法

I have a simple server which has this method

app.post('/', function (req, res) {
    res.sendfile(path.resolve(req.files.image.path));
});

如何在Image对象的客户端获取数据?
这是我的ajax.success方法,至少我试过...

How do I get data, on client side in Image object? this is my ajax.success method,at least what i tried...

success: function (res) {
    console.log(res);
    var canvas = document.getElementById("mainCanvas");
    var ctx = canvas.getContext("2d");
    var img = new Image();
    img.onload = function () {
        ctx.drawImage(img,0,0);
    }
    img.src=res
}

真的看已经有2天的答案...尝试了很多方法,但都没有奏效。我甚至不确定从服务器收到什么 - 它是字节数组吗?

Really looking for answer already for 2 days... tried a lot of ways, but none worked. I am not even sure what I receive from server - is it bytes array?

解决方案:
所以,我想通了post请求不需要发送文件,Image.src将自己的get请求发送到服务器

SOLUTION: so, i figured out that post request does not need to send file back, Image.src sends its own get request to server

app.post('/', function (req, res) {
res.send(path.basename(req.files.image.path));
});
/* serves all the static files */
app.get(/^(.+)$/, function(req, res){ 
     console.log('static file request : ' + req.params);
     res.sendfile( __dirname + req.params[0]); 
});

客户:

success: function (res) {
                var canvas = document.getElementById("mainCanvas");
                var ctx = canvas.getContext("2d");
                var img = new Image();
                console.log(res);
                img.onload = function () {
                    ctx.drawImage(img,0,0);
                }
                img.src="/uploads/"+res;
            }


推荐答案

您正试图设置 src 图像的属性为您返回的图像的字节代码,这将无法正常工作。您需要将其设置为要显示的图像的路径。 Image对象将自己对服务器执行GET请求,因此不需要ajax请求。以下内容适用于您:

You are trying to set the src attribute of the image to the byte code of the image you returned, which will not work. You need to set it to the path of the image that you want to display. The Image object will perform a GET request to your server on its own, so there is no need for an ajax request. Something like the following should work for you:

客户:

var canvas = document.getElementById("mainCanvas");
var ctx = canvas.getContext("2d");

var img = new Image();
img.src = "/imagepath.png";

img.onload = function () {
    ctx.drawImage(img,0,0);
}

服务器:

app.get('/imagepath.png', function (req, res) {
    res.sendfile(path.resolve(path.resolve(__dirname,'/imagepath.png')));
});

这篇关于如何在javascript中打开图像,由express.js sendfile函数发送[+解决方案]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆