POST text data as file in form

2019-06-03 18:10发布

问题:

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

回答1:

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