2

Is it possible to POST some XML data i have as string as file input type from a html form.

The case is i have a form like

form action="target.php" method="post" enctype="multipart/form-data">
   <input type="file" name="file" id="file"><br>
   <input type="submit" name="submit" value="Submit">
</form>

I have some xml data as string in my javascript code and i want to sent that string from the form as if it was uploading as a file with the file input tag

Thanks

2
  • With ajax you can but not with a regular form submit. Commented Apr 25, 2013 at 19:59
  • Yes with ajax is what i am looking for.Can you drop me some pointers how to do this with ajax.Thanks Commented Apr 26, 2013 at 9:02

1 Answer 1

2

If your browsers supports XMLHttpRequest level 2 and the html5 FileApi you can do the following

var xhr = new XMLHttpRequest;
var blob = new Blob([xmlString], {type:'text/xml'});
var data = new FormData();
data.append('file', blob, 'filename.xml');
xhr.open('POST',url, true);
xhr.send(data);

If your browser doesn't support these apis then you'll have to build your post body manually

var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
var boundary = '----'+(new Date()).getTime();
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary='+boundary);
var data = ['--'+boundary,
    'Content-Disposition: form-data; name="file"; filename="filename.xml"',
    'Content-Type: text/xml','',xmlString,'--'+boundary+'--',''].join('\r\n');
xhr.send(data);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes the manual way works well.I already implemented that way.Anyways thanks for the answer :)

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.