我正在尝试使用FileTransfer method将文件从PhoneGap上传到服务器。我需要为此上传启用HTTP基本身份验证。
以下是相关代码:
var options = new FileUploadOptions({
fileKey: "file",
params: {
id: my_id,
headers: { 'Authorization': _make_authstr() }
}
});
var ft = new FileTransfer();
ft.upload(image, 'http://locahost:8000/api/upload', success, error, options);
Looking over the PhoneGap source code我似乎可以通过在“params”列表中包含“标题”来指定授权标题,如上所述:
JSONObject headers = params.getJSONObject("headers");
for (Iterator iter = headers.keys(); iter.hasNext();)
{
String headerKey = iter.next().toString();
conn.setRequestProperty(headerKey, headers.getString(headerKey));
}
但是,这似乎并没有真正添加标题。
那么:对于iPhone和Android,有没有办法使用PhoneGap的FileTransfer进行HTTP基本身份验证?
答案 0 :(得分:9)
您可以添加自定义标题,方法是将其添加到选项而不是参数,如下所示:
authHeaderValue = function(username, password) {
var tok = username + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
};
options.headers = {'Authorization': authHeaderValue('Bob', '1234') };
答案 1 :(得分:0)
headers数组的正确位置是选项的直接子项。选项 - >报头。不是选项 - > params->标头。这是一个例子:
//**************************************************************
//Variables used below:
//1 - image_name: contains the actual name of the image file.
//2 - token: contains authorization token. In my case, JWT.
//3 - UPLOAD_URL: URL to which the file will be uploaded.
//4 - image_full_path - Full path for the picture to be uploaded.
//***************************************************************
var options = {
fileKey: "file",
fileName: 'picture',
chunkedMode: false,
mimeType: "multipart/form-data",
params : {'fileName': image_name}
};
var headers = {'Authorization':token};
//Here is the magic!
options.headers = headers;
//NOTE: I creaed a separate object for headers to better exemplify what
// is going on here. Obviously you can simply add the header entry
// directly to options object above.
$cordovaFileTransfer.upload(UPLOAD_URL, image_full_path, options).then(
function(result) {
//do whatever with the result here.
});
以下是官方文档:https://github.com/apache/cordova-plugin-file-transfer
答案 2 :(得分:0)
您可以自己创建授权标头。但您也可以在网址中输入凭据,如下所示:
var username = "test", password = "pass";
var uri = encodeURI("http://"+username + ':' + password +"@localhost:8000/api/upload");
请参阅FileTransfer.js以了解实现(第45行):
function getBasicAuthHeader(urlString) {
var header = null;
// This is changed due to MS Windows doesn't support credentials in http uris
// so we detect them by regexp and strip off from result url
// Proof: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a327cf3c-f033-4a54-8b7f-03c56ba3203f/windows-foundation-uri-security-problem
if (window.btoa) {
var credentials = getUrlCredentials(urlString);
if (credentials) {
var authHeader = "Authorization";
var authHeaderValue = "Basic " + window.btoa(credentials);
header = {
name : authHeader,
value : authHeaderValue
};
}
}
return header;
}