2

I am sending data via ajax to post in mysql. In this context how to inlude image file contents ?

If i use like : var formData = document.getElementById("img_file");
alert(formData.files[0]);

, i get error . Note : img_file is the id of the file dom. Any idea about this ?

3
  • Possible duplicate of stackoverflow.com/questions/942105/file-data-from-input-element Commented Feb 9, 2017 at 14:04
  • "i get error" – What error?! Commented Feb 9, 2017 at 14:12
  • @Quentin, i could not extract the file details from that data set. It was the real trouble and error. Commented Feb 9, 2017 at 18:23

2 Answers 2

5

You can use javascript FileReader for this purpose. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

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");
                }
            }

        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.