Ale*_*one 3 javascript node.js express
我有一个简单的服务器有这个方法
app.post('/', function (req, res) {
res.sendfile(path.resolve(req.files.image.path));
});
Run Code Online (Sandbox Code Playgroud)
如何在客户端的 Image 对象中获取数据?这是我的 ajax.success 方法,至少我尝试过......
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
}
Run Code Online (Sandbox Code Playgroud)
真的已经寻找答案两天了......尝试了很多方法,但没有奏效。我什至不确定我从服务器收到的是什么 - 是字节数组吗?
解决方案: 所以,我发现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]);
});
Run Code Online (Sandbox Code Playgroud)
客户:
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;
}
Run Code Online (Sandbox Code Playgroud)
您试图将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);
}
Run Code Online (Sandbox Code Playgroud)
服务器:
app.get('/imagepath.png', function (req, res) {
res.sendfile(path.resolve(path.resolve(__dirname,'/imagepath.png')));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9010 次 |
| 最近记录: |