使用 ajax 上传图像仅适用于 png

Upload image with ajax only works png

我尝试使用 AJAX 上传图片(和更多文本数据)并且它有效...但仅适用于 png。嗯...我只尝试了 png 和 jpg,而 jpg 不起作用。 我没有使用表格。这是我的 javascript 代码:

if(window.FileReader)
{
    reader = new FileReader();
    reader.onloadend = function(e)
    {
        data["image"] =  e.target.result.replace('data:image/png;base64,', '');
        $.post('/notifications/simple_message', data, function(result){
           console.log(result);
        });
    };
    reader.readAsDataURL(img);
}   

在服务器端(使用节点)我有这个:

if(req.body.image)
{
    var date = new Date();
    var buf = new Buffer(req.body.image, 'base64');
    image = req.session.user.name+'-'+date.getTime()+'.png';
    fs.writeFile('./public/images/users/'+image, buf);
}

我正在为新文件使用 png 扩展名...但我尝试使用 jpg 但它不起作用。
有什么想法吗??

谢谢!!

这一行是原因:

data["image"] = e.target.result.replace('data:image/png;base64,', '');

当它是 PNG 时,您只是删除数据 URI 的 header。使它更通用:

data["image"] = e.target.result.replace(/^data:.*?;base64,/, '')

谢谢@aaronk6。最后我做了这个(并且工作 jeje):

客户:

var ext = img.type.split('image/')[1];
data["ext"]   = ext;
data["image"] =  e.target.result.replace('data:image/'+ext+';base64,', '');

服务器

if(req.body.image)
{
    var date = new Date();
    var buf = new Buffer(req.body.image, 'base64');
    image = req.session.user.name+'-'+date.getTime()+'.'+req.body.ext;
    fs.writeFile('./public/images/user/'+image, buf);
}

真的,非常感谢