PhoneGap:使用multipart/form-data将文件上传到服务器
正在关注this尚未回答的问题我运行了一些测试以查看问题出在哪里 - 在我身边或服务器端。PhoneGap:使用multipart/form-data将文件上传到服务器
因此,考虑到它可能是一个图像编解码器问题,我试图上传一个text/plain
文件到我的服务器使用post方法。
首先,我确信该文件存在通过调用readAsText()
方法:
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("textfile.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
alert("Read as data URL");
alert(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
alert("Read as text");
alert(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
alert(evt.target.error.code);
}
后,我得到的文本文件的URL和文本文件内容的警告,我知道这是我的文件。现在我上传:
function gotFile(file){
// alert('gotFile')
// readDataUrl(file);
// readAsText(file);
alert(file.fullPath)
uploadText(file.fullPath)
}
function uploadText(fileURI) {
alert('uploading file...')
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
alert("http_status = " + error.http_status);
alert("upload error source " + error.source);
alert("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("https://mysecureurl.com/?filename="+options.fileName), win, fail, options);
}
我收到文件传输错误代码1(未找到文件),HTTP状态代码411(异常请求)。
我有我的Android项目中的所有权限,包括fileTransfer
以及<access origin="*"/>
。我的服务器管理员说他得到了请求,但是当我从phonegap发送文件时(与正常的浏览器请求不同),中间出现了一些问题,他无法弄清楚它是什么。
我真的被困在这里。有没有我不知道的PhoneGap限制?或者无论如何捕捉手机的http正文请求,所以我可以调试它?
问题在于内容类型。 Phonegap设置Content-Type:multipart/form-data; boundary = +++++省略两者之间的空格。有些服务器可能会因此而挑剔。我通过重写这个头文件并添加一个空白符号来解决这个问题,如下所示:Content-Type:multipart/form-data;边界= +++++。虽然这听起来像是黑客攻击,并为我解决了这个问题,但是这个改变需要在未来的版本中整合到phonegap Android库中。
它刚刚在Android平台上发生,并在iOS上很好,所以尝试设置options.chunkedMode=false
仅在Android (chunkedMode选项默认为true)。见https://github.com/apache/cordova-plugin-file-transfer/pull/141#issuecomment-291776345