POST text data as file in form

放肆的年华 提交于 2019-12-06 13:23:04

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!