如果在iOS& amp;上的网络应用中使用FormData发送文件,则文件转换为[Object object]字符串安卓 [英] File converted to [Object object] string if sent using FormData in web app on iOS & Android
问题描述
我正在构建基于Cordova/PhoneGap的Web应用程序,该应用程序使用多部分/表单数据POST请求将文件上传到服务器.
I am building a web app based on Cordova/PhoneGap which uploads files to a server using a multipart/form-data POST request.
以下代码可在BlackBerry 10上使用:
The following code works on BlackBerry 10:
var postRequest = new XMLHttpRequest();
if (postRequest.overrideMimeType) {
postRequest.overrideMimeType('text/xml');
}
var fd = new FormData();
fd.append('param1', 'value1');
[...]
fd.append('file', file, fileName);
postRequest.open('POST', url, true);
postRequest.send(fd);
但是,在运行iOS6的iPhone上,当将 File
对象发送到服务器时,它会由 String
[Object object]替换,类似于 Safari在以下情况下将文件转换为[object Object]插入FormData中.如何解决?.
However on an iPhone running iOS6 the File
object is replaced by the String
[Object object] when sent to the server, similar to the issue described in Safari converts File to [object Object] when inserted into FormData. How to fix?.
与该问题相反,我没有克隆File对象.通过在...中打开"菜单使用其他应用程序中的文档调用我的应用程序.我通过了一个本地文件系统URI,可以使用 window.resolveLocalFileSystemURI()
进行解析.这可以完美地工作,我首先收到一个FileEntry,然后从该File对象收到一个.但是,似乎无法正确识别该对象,并且在将请求传输到服务器时调用了它的 toString()
方法.
In contrast to that issue I am not cloning the File object. My app is invoked with documents from other apps via the "Open in..." menu. I am passed a local file system URI which I resolve using window.resolveLocalFileSystemURI()
. This works perfectly and I receive first a FileEntry and from that a File object. However it appears this object is not recognized correctly and its toString()
method is called instead when transmitting the request to the server.
这是iOS上的错误吗?还是在创建File对象时PhoneGap中的错误?最好的解决方法是什么?
Is this a bug on iOS? Or maybe a bug in PhoneGap when creating the File object? What is the best workaround?
更新:我只是在Android上遇到了相同的问题,因此该问题似乎并非特定于iOS.
UPDATE: I just ran into the same problem on Android, so this problem doesn't seem to be specific to iOS.
推荐答案
iOS可能的解决方法似乎是使用FileReader读取文件,从中构造一个新的Blob对象,然后将其传输到服务器:>
A possible workaround for iOS seems to be to read the file using FileReader, construct a new Blob object from it and then transmit this to the server instead:
var reader = new FileReader();
reader.onloadend = function(evt) {
var fileBlob = new Blob([evt.target.result], { 'type' : fileType });
};
reader.readAsArrayBuffer(file);
此处使用的Blob构造函数需要iOS 6.0或更高版本.这样,数据就可以按照预期的方式完全传输到服务器了.
The Blob constructor used here requires iOS 6.0 or higher. This way the data was completely transmitted to the server as intended.
也可以使用WebKitBlobBuilder在Android上创建Blob.不幸的是,在我进行测试时,这并不能解决Android上的问题.
A Blob can be created on Android, too, using WebKitBlobBuilder. Unfortunately this didn't fix the problem on Android during my tests.
这篇关于如果在iOS& amp;上的网络应用中使用FormData发送文件,则文件转换为[Object object]字符串安卓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!