How to get all Files Save in Dropbox to my HTML Page - javascript

i have save Images in Dropbox using Javascript like that
document.forms.newsletter.addEventListener('submit', function
cb(evt) {
//evt.preventDefault()
// API key from here: https://dropbox.github.io/dropbox-api-v2-
explorer/#files_upload
// need to consider how this gets secured
var TOKEN = ''
var dir = 'blackground/'
var file = document.getElementById('file').files[0]
var promise = new Promise(function (resolve, reject) {
// Dropbox requires application/octet-stream
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
}
else {
reject(xhr.response || 'Unable to upload file');
}
};
xhr.open('POST',
'https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'Bearer ' + TOKEN);
xhr.setRequestHeader('Content-Type', 'application/octet-
stream');
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({
path: '/' + dir + file.name,
mode: 'add',
autorename: true,
mute: false
}));
xhr.send(file);
})
promise
.then(function (result) {
// Save dropbox response to form
document.getElementById('dropbox').value =
JSON.stringify(result)
// Submit form on successful upload
evt.target.submit()
})
.catch(function (err) {
console.log('a');
})
return false
})
It works fine. But i want to retrieve each Image using Javascript and ajax to display it in my Web Page. How to make it?
I read this Documentation https://www.dropbox.com/developers-v1/core/docs#files-GET that we can make it with Get Verb.
I have make a Get for the API to get All Image like so
$.ajax({
method: "GET",
url: "https://content.dropboxapi.com/1/files/auto/blackground",
dataType: "json",
ContentType:"application/octet-stream",
Authorization:"Bearer token"
});
i get this Error
{error: "Authentication failed"}
error
:
"Authentication failed"
blackground is the folder where are all the Images
Something can help please

It works fine now. I make it like so. Token is my Token for Dropbox.
var token = '';
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var imageUrl = (window.URL || window.webkitURL).createObjectURL(xhr.response);
// display, assuming <img id="image"> somewhere
document.getElementById('image').src = imageUrl;
// download via the download attribute: limited browser support
var a = document.createElement('a');
//a.download = 'test.png';
//a.href = imageUrl;
//a.click();
}
};
xhr.open('POST', 'https://content.dropboxapi.com/2/files/download');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({ path: '/blackground/blackground_logo.jpg' }));
xhr.send();

Related

How to send a url in form-data as a file using js or axios

Am using vuejs and axios to send formdata to somelink.The file not sending and am getting the error
The parameter 'file' had the following problems: file transferred without multipart should be base64 encoded
I did change the data.append('file', url) and added another parameter to be like data.append('file', url,{type:'pdf'}) but then i get an error that say the second parameter is not a blob.
I know that the issue is caused because i use a url inside a file and this i cannot change because the api document that am sending files to require to send formdata with file so am trying to replace the file with a live url
var data = new FormData();
var url= 'https://storage.cloudconvert.com/xxxxx.pdf';
data.append('name','file')
data.append('filename', 'amjad');
data.append('file', url);
data.append('saved', 'true');
data.append('type', 'pdf');
axios.post('myapiurl',data, {
headers: {
'Content-Type': 'multipart/form-data'
},
}).then(res => {
console.log(res);
})
Try opening the file and then encoding it.. something like this..
function getPdf(){
// read text from URL location
var request = new XMLHttpRequest();
request.open('GET', 'https://storage.cloudconvert.com/xxxxx.pdf', true);
request.send(null);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var type = request.getResponseHeader('Content-Type');
if (type.indexOf("pdf") !== 1) {
return request.responseText;
}
}
}
}
// Encode the String
var pdf = btoa(getPdf());
var data = new FormData();
data.append('name','file')
data.append('filename', 'amjad');
data.append('file', pdf);
data.append('saved', 'true');
data.append('type', 'pdf');
axios.post('myapiurl',data, {
headers: {
'Content-Type': 'multipart/form-data'
},
}).then(res => {
console.log(res);
})

React remote request with authorization

I want to do a remote request using React JS. I try to do it as follows:
let username = 'some-username';
let password = 'some-password';
let url = 'some-url';
fetch(url', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic '+btoa(username + ":" + password),
},
}).then(response => {
debugger;
return response.json();
}).then(json => {
debugger;
});
I get an error:
If I do the same request with the same credentials with postman it works:
Any idea?
UPDATE
let user = 'some-user';
let password = 'some-password';
let url = 'some-url';
let req = new XMLHttpRequest();
let body = '';
if ('withCredentials' in req) {
req.open('GET', url, true);
req.setRequestHeader('Content-Type', 'application/json');
req.setRequestHeader('Authorization', 'Basic '+ btoa(user + ":" + password));
req.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
req.onreadystatechange = () => {
debugger;
if (req.readyState === 4) {
///////////////// it comes here but req.status is 0
if (req.status >= 200 && req.status < 400) {
debugger;
// JSON.parse(req.responseText) etc.
} else {
// Handle error case
}
}
};
req.send(body);
}
This is what I see in network tab:
You are having CORS problems. This is why it's working with Postman, it skips that check (OPTIONS call to the same request instead the GET one) and your React App (or any Javascript Ajax call ) fails, because your browser is checking it before launch the request..
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
This post shows how to deal with CORS
https://www.eriwen.com/javascript/how-to-cors/

how receive http response of binary pdf and show it. angular 2 - ionic2

I am tring to recive a pdf convert to binary(64) from a rest service, and show it in ionic 2, i try this:
I am tring to recive a pdf convert to binary(64) from a rest service, and show it in ionic 2, i try this:
in service
function(token:String, docCaseNumber: String){
this.setTokenHeaders(token);
this.headers.append('Accept', 'application/octet-stream');
let options = new RequestOptions({ headers: this.headers });
return new Promise(resolve => {
this.http.get(url, options)
.map(res => res)
.subscribe(data => {
//console.log(data);
resolve(data.text());
}, err => {
resolve("connException");
});
});
}
in component
getXX(){
this.miservice.functoin(this.token, 'H17-09601').then(
(data) => {
var blob = data;
console.log(blob);
this.base64ToUint8Array(data);
//this.getBase64(data);
var converted = new Blob([blob], {type:'application/pdf'});
this.convertToBase64(converted);
//this.base64ToUint8Array(converted);
//this.fileURL = URL.createObjectURL(converted);
//window.open(fileURL);
var pdf = pdfMake.createPdf(this.buildPdf(converted));
pdf.getBase64(function (output) {
this.base64ToUint8Array(output);
});
//console.log(pdf);
pdf.open;
//console.log(data);
});
}
here is the answer. You can use this for show pdf
Modify according to your needs ;)
return new Promise(resolve => {
let xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.setRequestHeader("Access-Control-Allow-Origin", '*');
xhr.setRequestHeader('Accept', 'application/octet-stream');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
// xhr.overrideMimeType('text/xml; charset=iso-8859-1');
xhr.overrideMimeType('text/xml; charset=iso-8859-1');
xhr.responseType = "arraybuffer";
xhr.onreadystatechange= function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(JSON.stringify((xhr.response)));
resolve(new Blob([xhr.response], { type: 'application/pdf' }));
} else {
//do something
}
}
}
xhr.send();
});
then use it like this:
your-function.then(
(blob :Blob) => {
var downloadUrl = URL.createObjectURL(blob);
var downloadLink = document.createElement('a');
downloadLink.href = downloadUrl;
downloadLink.target = '_blank';
document.body.appendChild(downloadLink);
downloadLink.click();
});

nodejs xhr POST

I am using nodejs and trying to make a POST command to a server. I am also using node-xmlHttpRequest (driverdan's module). I am having issues with the content-type and get the error:
{
"response":{
"errorCode":"UNKNOWN_ERROR","message":"Content type
'text/plain;charset=UTF-8' not supported","detail":"Content type
'text/plain;charset=UTF-8' not supported"
},"version":"1.0"
}
I need the content-type to be JSON, not text. I have tested the code with GET and it works fine.
Here is my code:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
var sys = require('util');
var json_text2 = { "username": "admin","password": "-----" };
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
//- var xmlHTTP = new XMLHttpRequest();
xhr.onreadystatechange = function() {
sys.puts("State: " + this.readyState);
if (this.readyState === 4) {
sys.puts("Complete.\nBody length: " + this.responseText.length);
sys.puts("Body:\n" + this.responseText);
}
};
xhr.open("POST",apic_url,true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Accept","application/json");
xhr.responseType = 'JSON';
xhr.send(JSON.stringify(json_text2));
app.locals.apic_nd = xhr.responseText;
Any ideas?
Thanks to jfriend00 I got it working (not sure how to upvote his comment. But here is the code I used:
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
var request = require('request');
var options = {
url: 'https://'+apicem_ip+'/api/v1/ticket',
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: '{ "username": "admin", "password": "----"}'
};
function callback(error, response, body) {
console.log("callback function");
if (!error) {
var info = (JSON.parse(body));
console.log(info);
console.log("status 200");
}
else {
console.log(JSON.parse(body));
}
}
request.post(options, callback);

Can open blob returned by XMLHTTPRequest, but can't upload to Azure

I am able to upload a file to my vendors API, and the vendor responds with a .png file as binary data. I am able to write this out to a blob in the browser, but I can't get it to upload in Azure blob storage. I also tried uploading it to a Web directory using fs.writefile but that produces a corrupt/non-bitmap image.
Ideally, I would like to upload my blob directly into Azure, but when I try it gives me the following error:
TypeError: must start with number, buffer, array or string
If I need to upload the blob to a Web directory and use Azure's createBlockBlobFromLocalFile, I would be more than happy to, but my attempts have failed thus far.
Here is my XMLHTTPRequest that opens the image in the browser that is returned after I post my file:
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function (ev) {
var oData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("POST", "http://myvendorsapi/Upload", true);
xhr.onload = function (oEvent) {
if (xhr.status == 200) {
var blob = new Blob([xhr.response], { type: "image/png" });
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
console.log(blob);
var containerName = boxContainerName;
var filename = 'Texture_0.png';
$http.post('/postAdvanced', { containerName: containerName, filename: filename, file: blob }).success(function (data) {
//console.log(data);
console.log("success!");
}, function (err) {
//console.log(err);
});
} else {
oOutput.innerHTML = "Error " + xhr.status + " occurred when trying to upload your file.<br \/>";
}
};
xhr.send(oData);
ev.preventDefault();
}, false);
Here is my Node backend for the /postAdvanced call:
app.post('/postAdvanced', function (req, res, next) {
var containerName = req.body.containerName;
var filename = req.body.filename;
var file = req.body.file;
if (!Buffer.isBuffer(file)) {
// Convert 'file' to a binary buffer
}
var options = { contentType: 'image/png' };
blobSvc.createBlockBlobFromText(containerName, filename, file, function (error, result, response) {
if (!error) {
res.send(result);
} else {
console.log(error);
}
});
})
If someone can't help me with uploading directly to Azure, if I can get how to upload this blob to a directory, I can get it into Azure via createBlockBlobFromLocalFile
I have solved the issue. I needed to base64 encode the data on the client side before passing it to node to decode to a file. I needed to use XMLHTTPRequest to get binary data properly, as jQuery AJAX appears to have an issue with returning (see here: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/).
Here is my front end:
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function (ev) {
var oData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("POST", "http://vendorapi.net/Upload", true);
xhr.onload = function (oEvent) {
if (xhr.status == 200) {
var blob = new Blob([xhr.response], { type: "image/png" });
//var objectUrl = URL.createObjectURL(blob);
//window.open(objectUrl);
console.log(blob);
var blobToBase64 = function(blob, cb) {
var reader = new FileReader();
reader.onload = function() {
var dataUrl = reader.result;
var base64 = dataUrl.split(',')[1];
cb(base64);
};
reader.readAsDataURL(blob);
};
blobToBase64(blob, function(base64){ // encode
var update = {'blob': base64};
var containerName = boxContainerName;
var filename = 'Texture_0.png';
$http.post('/postAdvancedTest', { containerName: containerName, filename: filename, file: base64}).success(function (data) {
//console.log(data);
console.log("success!");
// Clear previous 3D render
$('#webGL-container').empty();
// Generated new 3D render
$scope.generate3D();
}, function (err) {
//console.log(err);
});
})
} else {
oOutput.innerHTML = "Error " + xhr.status + " occurred when trying to upload your file.<br \/>";
}
};
xhr.send(oData);
ev.preventDefault();
}, false);
Node Backend:
app.post('/postAdvancedTest', function (req, res) {
var containerName = req.body.containerName
var filename = req.body.filename;
var file = req.body.file;
var buf = new Buffer(file, 'base64'); // decode
var tmpBasePath = 'upload/'; //this folder is to save files download from vendor URL, and should be created in the root directory previously.
var tmpFolder = tmpBasePath + containerName + '/';
// Create unique temp directory to store files
mkdirp(tmpFolder, function (err) {
if (err) console.error(err)
else console.log('Directory Created')
});
// This is the location of download files, e.g. 'upload/Texture_0.png'
var tmpFileSavedLocation = tmpFolder + filename;
fs.writeFile(tmpFileSavedLocation, buf, function (err) {
if (err) {
console.log("err", err);
} else {
//return res.json({ 'status': 'success' });
blobSvc.createBlockBlobFromLocalFile(containerName, filename, tmpFileSavedLocation, function (error, result, response) {
if (!error) {
console.log("Uploaded" + result);
res.send(containerName);
}
else {
console.log(error);
}
});
}
})
})

Categories

Resources