JavaScript 如何将 Base64 URL 转换为文件?

3
我正在从数据库中检索文件数据,并需要将其发送到前端(我的前端具有下载操作以下载文件)。如何将这些类型的URL转换为文件。我希望可以在任何文件类型(doc、txt、jpg、pdf、zip等)中使用。
"data:text/plain;charset=utf-8;base64,MzQuNjIzNjU..................."

这是我的实现。它对 txt 文件起作用,但由于某些原因它不能处理 jpg 和其他文件类型。有人能帮我找出问题所在吗?(我认为这可能是编码或解码问题)谢谢:)

        let mime = file.url.split(',')[0].split(':')[1].split(';')[0];
        console.log(mime);
        let content = unescape(encodeURIComponent(file.url.split(',')[1]));
        content = Buffer.from(content, 'base64').toString();

        console.log(content);

        let temp = mime + ";charset=UTF-8";
        res.set('Content-Type', temp);
        res.set('Content-Disposition','attachment; filename=' + file.name );
        res.send(content);
2个回答

0

您可以使用 content = new Buffer(content, 'base64')

如果您想将其保存到文件中,可以使用以下代码:

/* name is the name of the file you want to save your file in.*/
fs.writeFile(name , content, {encoding: 'base64'}, function(err){
  if (err) console.log('err', err);
  console.log('success');
});

0

尝试使用以下代码,希望能够解决问题:

 //return a promise that resolves with a File instance
    function urltoFile(url, filename, mimeType){
        return (fetch(url)
            .then(function(res){return res.arrayBuffer();})
            .then(function(buf){return new File([buf], filename,{type:mimeType});})
        );
    }
    
    //Usage example:
    urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')
    .then(function(file){ console.log(file);});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接