I can't find in create and update methods of Google Drive API, where should I put actual text that I want to be inside my text file. Where is this parameter?
With this query I only create empty file:
await window.gapi.client.drive.files.create({
resource: {
'name': `${knowledgeFile.id}.txt`,
'parents': [`${srcDataFolderId}`]
},
media: {
mimeType: 'text/plain',
body: convertHTMLToPlainText(knowledgeFileHTML)
},
fields: 'id'
})
After creating a text file on your drive, you can update its content with the Files: update request
To do so
Specify the new content as a string
Transform the content string into a byte array
Get the existing file by its id
Read the file as binary string with FileReader
Create a new file metadara as a bytearray merging the old and the new contents
Perform an Files:Update request specifying the new file metadata as request body
Sample
function updateFile() {
var fileId = "YOUR FILE ID";
var contentString = "Hello world";
var contentArray = new Array(contentString.length);
for (var i = 0; i < contentArray.length; i++) {
contentArray[i] = contentString.charCodeAt(i);
}
var byteArray = new Uint8Array(contentArray);
var newData = new Blob([byteArray], {
type: 'text/plain'
});
var request = gapi.client.drive.files.get({
'fileId': fileId
});
request.execute(function(oldData) {
var boundary = '-------314159265358979323846';
var delimiter = "\r\n--" + boundary + "\r\n";
var close_delim = "\r\n--" + boundary + "--";
var reader = new FileReader();
reader.readAsBinaryString(newData);
reader.onload = function(e) {
var contentType = newData.type || 'application/octet-stream';
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter + 'Content-Type: application/json\r\n\r\n' + JSON.stringify(oldData) + delimiter + 'Content-Type: ' + contentType + '\r\n' + 'Content-Transfer-Encoding: base64\r\n' + '\r\n' + base64Data + close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files/' + fileId,
'method': 'PUT',
'params': {
'uploadType': 'multipart',
'alt': 'json'
},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody
});
request.execute();
}
});
}
Related
I'm trying to use Microsoft Azure OCR API service to extract some text from an image.
The image I have for sending to the API service has a "data:image/png; base64, " structure and therefore I can't send it with content-type "application/json".
I tried sending it with content-type "multipart/form-data" or "application/octet-stream", but it also fails...
// this "url" gives me the "data:data:image/png;base64, " code
var sourceImageUrl = document.getElementById("myImage").src;
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(jqXHR){
jqXHR.setRequestHeader("Content-Type","multipart/form-data");
jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: [sourceImageUrl]
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ?
"Error. " : errorThrown + " (" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
(jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message :
jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
I am bit confused about how I should be sending the image or if I should do some transformations.
Which content-type should I be using to do a proper request?
Should I change the encoding of the image source? How?
Thank you all!
I finally got it working by adding a makeBlob function that returns a blob out of a base64 code. I also set the content-type to "application/octet-stream".
Final code looks like this:
function makeblob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
function recognizeText() {
imageToSend = image.src;
binDataImage = imageToSend.replace("data:image/png;base64,","");
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(jqXHR){
jqXHR.setRequestHeader("Content-Type","application/octet-stream");
jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: makeblob(binDataImage, 'image/jpeg'),
cache: false,
processData: false
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ?
"Error. " : errorThrown + " (" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
(jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message :
jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
};
i have an array of stores, where the address and some other things are stored.
Now I want to iterate through this array and geocode the lat / lng coords and save them to the database.
With the code below I get double or triple entries of the same store. Do I miss something with the scope here?
Thanks!
var promises = [];
data.forEach(function (element, index)
{
var addressString = element.plz + " " + element.stadt + "," + element.adresse;
var url = encodeURI("https://maps.googleapis.com/maps/api/geocode/json?address=" +
addressString);
var promise = Parse.Cloud.httpRequest({
method: "GET",
url:url
}).then(function (http) //SUCCESS
{
var geocodedObject = new Parse.Object("GeocodedStores");
geocodedObject.set("storeID", element.id);
geocodedObject.set("Latitude", http.data.results[0].geometry.location.lat);
geocodedObject.set("Longitude", http.data.results[0].geometry.location.lng);
return geocodedObject.save(null, {
useMasterKey: true
});
},
function (http, error)
{
response.error(error);
});
promises.push(promise);
});
return Parse.Promise.when(promises);
Finally found a working solution. It looked like it was a problem with the scope. I put the code in a seperate function and added this returned promise to an array.
var fn = function(element, geocodedObject)
{
var addressString = element.plz + " " + element.stadt + "," + element.adresse;
var url = encodeURI("https://maps.googleapis.com/maps/api/geocode/json?address=" +
addressString);
Parse.Cloud.httpRequest({
method: "GET",
url: url
}).then(function(http)
{
geocodedObject.set("storeID", element.id);
geocodedObject.set("Latitude", http.data.results[0].geometry.location.lat);
geocodedObject.set("Longitude", http.data.results[0].geometry.location.lng);
geocodedObject.set("address", addressString);
return geocodedObject.save(null, {
useMasterKey: true
});
});
}
var promises = [];
for (var k = 0;k<data.length;k++)
{
var geocodedObject = new Parse.Object("GeocodedStores");
promises.push(fn(data[k], geocodedObject));
}
Parse.Promise.when(promises).then(function () {
response.success("DONE");
});
Help, I need call the http.request for send Image captured in camera api in my NativeScript App.
I capture the photo in camera api for nativescript and need send to api in upload process.
Follow the code about this process:
var frameModule = require("ui/frame");
var viewModule = require("ui/core/view");
var Observable = require("data/observable").Observable;
var config = require("../../shared/config");
var cameraModule = require("camera");
var imageModule = require("ui/image");
var http = require("http");
exports.loaded = function(args) {
var page = args.object;
viewModel = new Observable({
coleta: config.id_coleta
});
page.bindingContext = viewModel;
};
exports.voltar = function() {
var topmost = frameModule.topmost();
topmost.navigate("views/ocorrencia/menuocorrencia");
};
function tapFoto() {
cameraModule.takePicture({
width: 300,
height: 300,
keepAspectRatio: true
}).then(function(picture) {
var image = new imageModule.Image();
image.imageSource = picture;
var item = {
itemImage: picture
};
var urlfoto = "http://192.1.1.1:8090/sendphoto/upload";
alert("URL: " + urlfoto);
http.request({
url: urlfoto,
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
},
content: ({uploadFile: image.imageSource, entrega: config.id_coleta})
}).then(function (response) {
var statusCode = response.statusCode;
alert("Codigo Retorno: " + statusCode);
alert("Foto registrada com sucesso.");
}, function (e){
alert("Erro: " + e);
});
});
}
exports.tapFoto = tapFoto;
I recommend using of nativescript-background-http plugin for uploading files.
tns plugin add nativescript-background-http
Here is your code modifed to work with the installed plugin:
"use strict";
var Observable = require("data/observable").Observable;
var cameraModule = require("camera");
var fs = require("file-system");
var bghttpModule = require("nativescript-background-http");
var session = bghttpModule.session("image-upload");
var viewModel = new Observable();
function navigatingTo(args) {
var page = args.object;
page.bindingContext = viewModel;
}
exports.navigatingTo = navigatingTo;
function onTap() {
cameraModule.takePicture({
width: 300,
height: 300,
keepAspectRatio: true
}).then(function (imageSource) {
console.log("Image taken!");
var folder = fs.knownFolders.documents();
var path = fs.path.join(folder.path, "Test.png");
var saved = imageSource.saveToFile(path, "png");
var request = {
url: "http://httpbin.org/post",
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"File-Name": "Test.png"
},
description: "{ 'uploading': " + "Test.png" + " }"
};
var task = session.uploadFile(path, request);
task.on("progress", logEvent);
task.on("error", logEvent);
task.on("complete", logEvent);
function logEvent(e) {
console.log("----------------");
console.log('Status: ' + e.eventName);
// console.log(e.object);
if (e.totalBytes !== undefined) {
console.log('current bytes transfered: ' + e.currentBytes);
console.log('Total bytes to transfer: ' + e.totalBytes);
}
}
});
}
exports.onTap = onTap;
I'm new to jquery/ajax/javascript. I try to get data from an API, everything works, except, I can't print the data to my html-page. Somehow the appendChild-method doesn't work. What do I do wrong here? Thanks in advance!
function openkvk() {
var urls = "https://overheid.io/api/kvk?";
var keyset = {
"ovio-api-key": '041be6bc5818ad9bfe0ff9c9a9637a24b2fd1ec817cd8c3d102f61afc8006dd2'
};
var postcode = document.getElementById('plaats').value;
var naam = document.getElementById('bedrijfsnaam').value;
var kvk = document.getElementById('kvk').value;
console.log("tot aan hier1");
if(postcode != ""){
urls = urls + "&filters[postcode]=" + postcode;
}
if(naam != ""){
urls = urls + "&filters[handelsnaam]=" + naam;
}
if(kvk != ""){
urls = urls + "&filters[dossiernummer]=" + kvk;
}
console.log("tot aan hier2");
$.ajax({
type: 'GET',
url: urls,
headers:{"ovio-api-key":'041be6bc5818ad9bfe0ff9c9a9637a24b2fd1ec817cd8c3d102f61afc8006dd2',"Content-Type":"application/json"},
dataType: 'json',
complete: function(data) {
var response = data.responseJSON;
console.log(response);
var container = document.getElementById('result-kvk');
container.innerHTML = "";
console.log(data);
console.log("data geprint");
$.each(response._embedded.rechtspersoon, function(index,item){
console.log(item);
console.log("items geprint");
var kvknummer = document.createElement("P");
kvknummer.innerHTML = item.dossiernummer;
//console.log(kvknummer);
var handelsnaam = document.createElement('P');
handelsnaam.innerHTML = item.handelsnaam;
console.log("hwiueh");
//failed
container.appendChild(kvknummer);
container.appendChild(handelsnaam);
});
}
});
}
Below is the piece of code i have used:
JSON.stringify({
request:
{
"Ticket": "String content",
"Picture": {
"Name": "blabla",
"ImgData": "blabla",
},
}
});
i have picture , i captured with phonegap and i wanna post it with json. is it possible ?
Upload/Post image using phonegap
function uploadPhoto(imageURI) {
var imagefile = imageURI;
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert($.parseJSON(r.response))
}
function fail(error) {
console.log("Response = " + error.code);
}
if you want to upload it inside json data you'll need to send the image encoded in base64, for that use the destinationType: Camera.DestinationType.DATA_URL when you take the picture