将文本数据作为文件形式发布 [英] POST text data as file in form

查看:121
本文介绍了将文本数据作为文件形式发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将一些XML数据作为字符串作为文件输入类型从HTML表单发布。

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

案例是我有一个像

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>

我的javascript代码中有一些xml数据作为字符串,我想从表单中发送该字符串就好像它是用文件输入标签上传文件一样

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

推荐答案

如果您的浏览器支持 XMLHttpRequest 2级和html5 FileApi 您可以执行以下操作:

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

如果您的浏览器不支持这些API,则必须手动构建您的帖子正文

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

这篇关于将文本数据作为文件形式发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆