简体   繁体   English

如何在javascript中读取HTML文件内容

[英]How to read HTML file contents in javascript

I am sending data via ajax to post in mysql.我正在通过ajax发送数据以在mysql中发布。 In this context how to inlude image file contents ?在这种情况下如何插入图像文件内容?

If i use like : var formData = document.getElementById("img_file");如果我使用类似: var formData = document.getElementById("img_file");
alert(formData.files[0]);警报(formData.files[0]);

, i get error . ,我得到错误。 Note : img_file is the id of the file dom.注意:img_file 是文件 dom 的 id。 Any idea about this ?对此有什么想法吗?

You can use javascript FileReader for this purpose.为此,您可以使用 javascript FileReader Here is a sample code demonstration.这是一个示例代码演示。

 <html> <body> <input type="file" id="fileinput" /> <div id="ReadResult"></div> <script type="text/javascript"> function readSingleFile(evt) { //Retrieve the first (and only!) File from the FileList object var f = evt.target.files[0]; if (f) { var r = new FileReader(); r.onload = function (e) { var contents = e.target.result; document.getElementById("ReadResult").innerHTML = contents; } r.readAsText(f); } else { alert("Failed to load file"); } } document.getElementById('fileinput').addEventListener('change', readSingleFile, false); </script> </body> </html>

Find more details here . 在此处查找更多详细信息。

i think it may help you.我认为它可以帮助你。

 $('#image').change(function () {
            $("#add").attr("disabled", true);
            var img = this.files[0];
            var reader = new FileReader;
            reader.readAsDataURL(img);
            reader.onload = function (e) {
                var file = new Image;
                file.src = e.target.result;
                file.onload = function () {
                    $("#height").text(file.height);
                    $("#width").text(file.width);
                    $("#imageprev").attr("src", file.src);
                    $("#upld").removeAttr("disabled");
                }
            }

        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM