2013-05-13 9 views
5

Devo accedere all'oggetto XMLHttpRequest non elaborato per aggiungere una richiamata di avanzamento caricamento file sui browser che la supportano. È possibile o devo costruire personalmente la richiesta non elaborata? In tal caso, come faccio a racchiudere un grezzo XMLHttpRequest in un oggetto promessa?

risposta

4

ho simulato la costruzione di un costume XMLHttpRequest in questo modo $http chiamata:

uploadFile(file, progressHandler) { 
    var xhr = new XMLHttpRequest(), 
     deferred = $q.defer(); 

    xhr.open("POST", "your/path", true); // method, url, async 
    xhr.setRequestHeader("Content-Type", file.type || "application/octet-stream"); 
    xhr.onreadystatechange = function (e) { 
    if (xhr.readyState == 4) { 
     $rootScope.$apply(function() { 
     // Construct a response object similar to a regular $http call 
     // 
     // data – {string|Object} – The response body transformed with the transform functions. 
     // status – {number} – HTTP status code of the response. 
     // headers – {function([headerName])} – Header getter function. 
     // config – {Object} – The configuration object that was used to generate the request. 
     var r = { 
      data: xhr.response, 
      status: xhr.status, 
      headers: xhr.getResponseHeader, 
      config: {} 
     }; 
     if (r.status == 200) { 
      deferred.resolve(r); 
     } else { 
      deferred.reject(r); 
     } 
     }); 
    } 
    }; 
    if (progressHandler && xhr.upload) { 
    xhr.upload.addEventListener('progress', function(e) { 
     progressHandler((e.loaded/e.total), e); 
    }, false); 
    } 
    // This is only available in XHR2, provide multipart fallback 
    // if necessary 
    xhr.send(file); 

    return deferred.promise; 
} 
+0

'getResponseHeader' non imita perfettamente' funzione headers' fornite in risposta normale. Potresti anche voler cambiare 'xhr.response' in' JSON.parse (xhr.response) 'e aggiungere' statusText' all'hash. –

Problemi correlati