on website working on, have download link, must served user. however, when fetching url server can either serve error message in json (the appropriate headers , appropriate http status code set) or serve file.
currently, using iframe download file, prevents viewing error message. while, can done in principle, cannot done cross-domain , reading error data seems different between browsers (as browser interpret json html , create html tags around it)
i have considered using xmlhttprequest2 download file, , serve user, downloaded file can large , thus, must streamed user.
therefore, i'm looking way either download file or read error message depending on http status code.
api setup
i'm able change api wishes, api designed public api , designed rest api. means, api should stay simple possible, , workarounds make specific client-side code work should not have cause hazzle other client-side (thus api , client-side code decoupled).
the file being downloaded encrypted on server, , can decrypted information given in url. therefore, chunked transfer difficult, extracting chunk require server decrypt whole file.
the appropriate headers , appropriate http status code set
if statement correct, use same concept preflighted requests cross-site requests. preflighted requests first send http request options
method resource on other domain, in order determine whether actual request safe send or not.
in case, instead of having options
request automatically send, send manually head
request. head
method identical get
except server not return message-body in response. informations contained in http headers in response head
request should identical information sent in response get
request. since you're fetching headers , not body, have no problem large or file, nothing downloaded except headers.
then, can read these headers or status code, , depending on result of manually preflighted request, decide if should either stream file user or fetch error message if you're encountering error.
a basic implementation without knowledge of project using status code following:
function candownloadfile(url, callback) { var http = new xmlhttprequest(); http.open('head', url); http.onreadystatechange = function() { if (http.readystate === xmlhttprequest.done) { callback(http.status); } }; http.send(); } var candownloadcallback = function (statuscode) { if (statuscode === 200) { // head request returned ok status code, same, // let's download file... } else { // head request returned else, wrong, // let's fetch error message , maybe display it... } }
Comments
Post a Comment