已关注 this尚未解答的问题我运行了一些测试来查看问题出在哪里 - 在我这边还是在服务器端。
所以考虑到可能是图像编解码器问题,我尝试上传一个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);
}
我收到 fileTransfer 错误代码 1(未找到文件)和 http 状态代码 411(格式错误的请求)。
我拥有所有权限,包括fileTransfer
在我的 android 项目中以及 <access origin="*"/>
。我的服务器管理员说他收到了请求,但当我从phonegap发送文件时(与正常的浏览器请求不同),中间有些东西被破坏了,他无法弄清楚它是什么。
我真的被困在这里了。是否存在我不知道的 PhoneGap 限制?或者是否有办法捕获手机的http正文请求以便我可以调试它?
最佳答案
问题出在内容类型上。 Phonegap 设置 Content-Type: multipart/form-data;boundary=+++++ 省略之间的空格。有些服务器可能对此很挑剔。我通过重写此 header 并添加空格解决了该问题,如下所示:Content-Type: multipart/form-data;边界=+++++。虽然这听起来像是一个 hack,并且为我解决了问题,但此更改需要在未来版本中合并到phonegap Android 库中。
关于javascript - 电话间隙 : uploading file to server using multipart/form-data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17990705/