下载通过输入字段上传的PNG文件



我通过上传了一个文件

<input> id="pdf" type="file"></input>

我可以通过访问它的内容

var inp = document.querySelector("#pdf");
var text = await inp.files[0].text()

当调用我的下载功能时;失败-网络错误";(Chromium(,而在Firefox中什么都不发生(函数返回undefined(。

download("viainput.png",text);

但我很难将同一个文件保存到文件系统中,我总是收到损坏的文件。我的下一步是通过webrtc将其作为编码文本发送给另一个用户

function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:image/png;base64,' + encodeURIComponent(text));
element.setAttribute('download', filename);

element.style.display = 'none';
document.body.appendChild(element);

element.click();

document.body.removeChild(element);
}

// Start file download.
download("hello.png",'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');

您当前的解决方案不起作用,因为您在应该使用base64编码的字符串中提供了URL编码的数据。但忘了这一点。data:URL大多已经成为过去(或应该成为过去(。

实现这一点的有效方法是而不是将图像编码为字符串。相反,直接使用从输入中获得的文件。

var file = inp.files[0] // this is what you use
// as second argument for `download`
function download(filename, blob) {
const link = document.createElement('a')
const url = URL.createObjectURL(blob)
link.href = url
link.download = filename
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(url) // if you're done with that file
}

您也可以将文件(原型为Blob(直接发送到WebRTC数据通道,然后在另一端,从接收到的Blob创建对象URL。

最新更新