Devil's Advocate Devil's Advocate - 6 months ago 11
HTML Question

Difference between Ajax file load and <input> file load?

I have some javascript that processes and validates some custom XML. Currently the reference to the file is hard coded using Ajax:

$.get("test.xml", {}, XmlOnLoad );


When I debug the value passed to XmlOnLoad is a
#document
with a
conentType
of
application/xml


I need to be able to load different files. I found the code here and tried to adapt it but I'm having an issue. When it passes to the XmlOnLoad it is a
file
with a
type
of
text/xml
. As a result, it fails when I use any XML functions like
childNodes()
. Here is the code as I have it now:

function readURL(input) {
if (input.files && input.files[0]) {
XmlOnLoad(input.files[0])
}
}


What can I do differently to get it to process successfully as an XML document?

Answer

You could try converting the file to a blob url and use $.get.

function readURL(input) {
    if (input.files && input.files[0]) {
        $.get(URL.createObjectURL(input.files[0]), {}, XmlOnLoad, 'xml' );
    }
}