POST text data as file in form

落爺英雄遲暮 提交于 2019-12-22 18:42:25

问题


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


来源:https://stackoverflow.com/questions/16223485/post-text-data-as-file-in-form

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