如何在javascript中打开图像,由express.js sendfile函数[+SOLUTION]发送
How to open image in javascript,sent by express.js sendfile function[+SOLUTION]
我有一个简单的服务器,它有这个方法
app.post('/', function (req, res) {
res.sendfile(path.resolve(req.files.image.path));
});
如何在客户端的Image对象中获取数据?这是我的成功方法,至少我试过了。。。
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
}
真的在寻找答案已经两天了。。。尝试了很多方法,但都没有成功。我甚至不确定我从服务器收到了什么——是字节数组吗?
解决方案:所以,我发现post请求不需要发回文件,Image.src将自己的get请求发送到服务器
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请求。以下内容应该适用于您:
客户端:
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')));
});
相关文章:
- 可以't让我的if语句处理js中的html表单输入
- 使用agility.js进行页面布局和合成
- 使用Clipboard.js复制span文本
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 强制模板刷新ember.js
- 如何编写HTML输入的JS内联
- Angular JS IE9 Hashbang url rewriting
- 使用JS将数组转换为json对象
- Node.js v6.2.0类扩展不是函数错误
- 当js函数's已执行
- 要求未定义JS回调参数
- 在自定义mean.io包中使用angular-chart.js作为依赖项
- 如何在javascript中打开图像,由express.js sendfile函数[+SOLUTION]发送
- dirname vs. 为 sendFile() Node.js提供根路径
- res.sendFile不是Node.js函数
- node.js TypeError:路径必须是绝对的,或者指定根目录到 res.sendFile [无法解析 JSON]
- NodeJS Express sendFile,包括外部JS文件
- Node.js: sendfile用于未知的文件类型
- Node.js -发送文件到客户端使用sendFile
- 当在express中使用sendfile作为到静态html文件的路由的一部分时,会下载相关的.js和.css文件,但它们