2012-04-25 26 views
8

Estoy intentando cargar un archivo desde PhoneGap a un servidor usando el FileTransfer method. Necesito autorización básica HTTP para habilitar esta carga.PhoneGap FileTransfer con autenticación básica HTTP

Aquí está el código correspondiente:

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 parece que puedo especificar la cabecera de autorización mediante la inclusión de "headers" en la lista de "params" como lo he hecho anteriormente:

 JSONObject headers = params.getJSONObject("headers"); 
     for (Iterator iter = headers.keys(); iter.hasNext();) 
     { 
     String headerKey = iter.next().toString(); 
     conn.setRequestProperty(headerKey, headers.getString(headerKey)); 
     } 

Sin embargo, esto no parece realmente agregar el encabezado.

Entonces, ¿hay alguna manera de hacer autenticación básica de HTTP con FileTransfer de PhoneGap, tanto para iPhone como para Android?

+0

Para cualquiera que se pregunte, este método mencionado anteriormente funciona para mí. Solo necesita agregar esto: 'params.headers = {Authorization: 'Basic' + creds}; options.params = params; ' – gabaum10

+0

encabezados deben ir a options.headers no agregados a options.params .____ – Adam

Respuesta

9

Puede agregar encabezados personalizados mediante su inclusión en las opciones en lugar de los params así:

authHeaderValue = function(username, password) { 
    var tok = username + ':' + password; 
    var hash = btoa(tok); 
    return "Basic " + hash; 
}; 

options.headers = {'Authorization': authHeaderValue('Bob', '1234') }; 
+0

FYI, estoy teniendo problemas con esto en iOS (a partir del 1/14/13). Funciona bien en Android y BB ... – gabaum10

+0

¿qué versión de phonegap estás usando? He tenido éxito en iOS con 2.3.0 – Ryan

+0

2.2.0 ... eso es interesante, ¿quizás debería intentar actualizar? ¿Estabas teniendo problemas antes con 2.2.0? – gabaum10

0

La ubicación correcta de la matriz cabeceras es como un hijo inmediato de opciones. opciones-> encabezados. No opciones-> params-> encabezados. Aquí está un ejemplo:

//************************************************************** 
//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. 
}); 

aquí es la documentación oficial: https://github.com/apache/cordova-plugin-file-transfer

0

Puede crear una cabecera de autorización a sí mismo. Pero también puede introducir las credenciales en la url de esta manera:

var username = "test", password = "pass";  
var uri = encodeURI("http://"+username + ':' + password +"@localhost:8000/api/upload"); 

Ver FileTransfer.js para la aplicación (línea 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; 
} 
Cuestiones relacionadas