我在网上找到的脚本的帮助下创建了一个文本生成器,该脚本允许用户编辑文本并将其导出为文档。我想添加“上传图像”选项,以允许用户上传图像并使用纯JavaScript在页面上显示图像。我尝试过的网站上有很多上传图片解决方案。他们允许我上传图像并将其显示在页面上,但是当我将页面导出为文档时,图像没有显示在文档中。我使用了this answer。我在“无法显示链接的图像”文档中看到此消息。 如何使用纯Javascript添加图像上传和显示选项,以将其导出为文本类似于以下文件的文档:Website,这是我的完整网站script。
/*upload image and display it script*/
<script>
function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}
}
previewFile(); //calls the function named previewFile()
</script>
<script>
function Export2Doc(element, filename = ''){
var preHtml = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
var postHtml = "</body></html>";
var html = preHtml+document.getElementById(element).innerHTML+postHtml;
var blob = new Blob(['\ufeff', html], {
type: 'application/msword'
});
// Specify link url
var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);
// Specify file name
filename = filename?filename+'.doc':'document.doc';
// Create download link element
var downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob ){
navigator.msSaveOrOpenBlob(blob, filename);
}else{
// Create a link to the file
downloadLink.href = url;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
document.body.removeChild(downloadLink);
}
</script>
<style>
/*change color and backgroung-color when editing */
[contenteditable="true"] {
background-color: DodgerBlue;
}
[contenteditable="true"]:focus {
background-color: white;
color : black;
}
span.a{
min-width:20px;
border:1px solid black;
color:white;
}
</style>
<body>
<div id="exportContent">
<!-- upload image and display it -->
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
<br>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
<span class="a" contenteditable="true">
when an unknown printer
</span> took a galley of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,
and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
<button onclick="Export2Doc('exportContent');">EXPORT DOCUMENT </button>
</body>