Title is 'Untitled' when uploading or updating a file using Google Drive API javascript? - windows-8

I have been working on G drive API and doing upload, download delete and update of files and folders using JavaScript for windows 8 . The two problems which I encountered are;
When I upload a file or folder it gets uploaded with a title "UNTITLED" , can you tell me what I am doing wrong.? my request looks like this;
WinJs.xhr ({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
type: "post",
headers: { "Authorization": "Bearer " + accessToken, },
data: { "mimeType": "application/vnd.google-apps.folder", "title": "sampleFolder2" } }).then
(function (success) {
var response = JSON.parse(success.response);
},
function (error) {
console.log(error);
});
When I download a file I get an encrypted or some unique type of response like if I download an JPEG image I get JFIF in response text. Can you please tell me why ? cant I get the file downloaded to my disk..?
Here is the complete function of insertion of file using media as uploadtype.
function insertFile(accessToken) {
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg", ".txt"]);
openPicker.pickSingleFileAsync().then(function (file) {
if (file) {
var tMeta = {
title: file.name,
mimeType: file.contentType,
description: "xyz description."
};
WinJS.xhr({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
type: "post",
headers: {
"Authorization": "Bearer " + accessToken,
'Content-Type': file.contentType,
'Title': file.name
},
body: tMeta,
}).then(function (success) {
var response = JSON.parse(success.response);
var file1 = response;
secondRequest(accessToken, file1 , file);
}, function (error) {
var x = 4;
});
}
});
}
function secondRequest(accessToken, file1,file) {
var x = 2;
var tMeta = {
title: file.name,
mimeType: file1.mimeType,
// description: "xyz description."
};
var URL = 'https://www.googleapis.com/upload/drive/v2/files/' + file1.id + '?uploadType=media'
WinJS.xhr({
url: URL,
type: "put",
headers: {
"Authorization": "Bearer " + accessToken,
'Content-Type': file1.mimeType,
'Title': file.name
},
body: tMeta,
data: MSApp.createFileFromStorageFile(file)
}).then(function (success) {
var secondResponse = JSON.parse(success.response);
var z = 3;
}), function (error) {
var x = 3;
}
}

If you would like to upload metadata with the file, you need to implement the multipart upload. It's explained on https://developers.google.com/drive/manage-uploads#multipart

Related

uploading files to endpoint from a static webpage

I am trying to upload files to an S3 endpoint from a static HTML page but the files are always malformed when I download them from the bucket. The relevant code is below - what am I doing wrong with fetch?
const onSubmitForm = function (e) {
const file = this.files[0];
const reader = new FileReader();
// reader.readAsText(file); // didn't work
reader.readAsDataURL(file); // also didn't work
reader.onload = async function () {
const bodyData = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
file: {
// the backend endpoint expects a base64 encoded img
// the upload completes but the
"data": reader.result.toString()
},
"name": file.name
})
}
const response = await fetch(uploadUrl, bodyData).then(
res => res.json()
);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
//
}

I'm trying to send an image using formdata and react native fetch and it's working on ios but not on android

I'm trying to send an image from react native to my server using fetch and it's working on ios but not android. i'm testing on physical devices. the error that is returned is a Network Error exception.
Also, I'm using fetch for all of my api calls, and all the POST requests where I'm sending just a JSON body are working fine, even on Android. It's just sending the image using fetch + formData that's not working on Android.
Some things I've tried are (mostly suggestions on other questions similar to this one)
[commenting out flipper in MainApplication][1]: https://stackoverflow.com/a/61126831/2395829
tried working with the XMLHttpRequest object directly
tried removing the headers in the post request
added android:usesCleartextTraffic="true" to AndroidManifest.xml
I've spent a few hours on this but can't get it to work...
It's possible some of the changes I made to AndroidManifest didn't get synced. I ran npm run android after changing file and it said the Gradle sync completed so I don't think that's too likely...
The code snippet below is where the formData object is created and the fetch request sent
const data = new FormData()
data.append('avatar', {
uri: res,
type: 'image/jpeg',
name: 'gravavatar',
uid: userData.id,
imagePos: idx,
})
fetch(global.BASE_URL + '/save_profile_image/' + userData.id + '/' + imagePos + '/no', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
// 'Access-Control-Allow-Origin': '*',
},
// make sure to serialize your JSON body
body: data
}).then(response => {
if (response.ok) {
// do stuff like setState
}
}).catch(err => {
console.log(err)
})
The entire function is below.
const _pickImage = async (idx) => {
try {
let result = null
try {
result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: false,
aspect: [4, 3],
quality: 0.05,
});
} catch (err) {
console.log('IMAGE FAILED')
console.log(err)
return;
}
if (!result.cancelled) {
let images = [...state.images];
images[idx] = result.uri
if (result.uri.slice(0, 4) == 'file') {
var xhr = new XMLHttpRequest();
xhr.open("GET", result.uri, true);
xhr.responseType = "blob";
xhr.onload = function(e) {
console.log(this.response);
var reader = new FileReader();
reader.onload = async function(event) {
var res = event.target.result;
var stringLength = res.length - 'data:image/png;base64,'.length;
var sizeInBytes = 4 * Math.ceil((stringLength / 3)) * 0.5624896334383812;
var sizeInKb = sizeInBytes / 1000;
// console.log(sizeInKb)
if (sizeInKb > 4999) {
alert('File is too large')
return;
}
const data = new FormData()
data.append('avatar', {
uri: res,
type: 'image/jpeg',
name: 'gravavatar',
uid: userData.id,
imagePos: idx,
})
fetch(global.BASE_URL + '/save_profile_image/' + userData.id + '/' + imagePos + '/no', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
// 'Access-Control-Allow-Origin': '*',
},
// make sure to serialize your JSON body
body: data
}).then(response => {
if (response.ok) {
// do stuff like setState
}
}).catch(err => {
console.log(err)
})
}
var file = this.response;
reader.readAsDataURL(file)
};
xhr.send()
}
return;
}
} catch (E) {
console.log(E);
}
};
Help would be much appreciated.
Thank you.

Error in uploading Multiple Images in ReactNative

const availabilityData = new FormData();
availabilityData.append('name', title);
availabilityData.append('foodType', foodType);
availabilityData.append('availability_type', category);
availabilityData.append('description', description);
availabilityData.append('total_quantity', quantity);
availabilityData.append('cooked_time', madeOn);
availabilityData.append('best_before', bestBefore);
availabilityData.append('storage_description', storageDesc);
availabilityData.append('latitude', fromLocation.latitude);
availabilityData.append('longitude', fromLocation.longitude);
availabilityData.append('city', selectedCity);
availabilityData.append('creator_delivery_option', deliveryOption);
for (let i = 0; i < imageLoc.length; i++) {
const newFile = {
uri: imageLoc[i],
type: 'image/jpg',
name: new Date(),
};
availabilityData.append('files[]', newFile);
}
await axios({
url: constants.BASE_URL + 'availability/createAvailability',
method: 'post',
data: availabilityData,
headers: {
Authorization: `UserData ${token}`,
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
})
.then(function (response) {
Alert.alert('Availability Created Successfully');
navigation.popToTop();
removeAllInputs();
setLoading(false);
})
.catch(function (error) {
console.log(error);
setLoading(false);
});
}
imageLoc is the State where I have stored the location of selected Images.
output when I print imageLoc:
["content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-151358739.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-151913720.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-15253326.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-152139570.jpg", "content://com.android.externalstorage.documents/document/primary%3ADCIM%2FCamera%2FWe4Us%2FWe4Us-1524187.jpg"]
Error I got in the backend
You are having Content-Provider paths in your file array. A content provider is not a valid url in Android and probably Axios is not prepared to handle them. In this case you can copy the files for example with react-native-fs to a different location:
RNFS.copyFile(uri, targetPath)
And then provide the targetPath to axios. Make sure to delete the copies after sending the images.

How to upload video directly from client browser to Viemeo using jquery?

I have try to upload a video to vimeo account directly from browser using api ,video details are created but file seems to corrupted/upload not happens.This is my sample code.
var file = $(this).prop("files")[0];
var formData = new FormData();
formData.append("file_data", file);
$.ajax({
url: "https://api.vimeo.com/me/videos/",
type: "post",
data: formData,
headers: {
"Authorization": "Bearer -----",
},
processData: false,
mimeType: "multipart/form-data",
contentType: false,
}).done(function (response) {
// Do something
}).complete(function (response) {
// Do something
}).fail(function (e) {
// Do something
});
vimeo video listing shows blank thumbnail
enter image description here
Try this piece of code. I have made some changes here:
var file = $(this).prop("files")[0];
var formData = new FormData();
formData.append("file_data", file);
$.ajax("https://api.vimeo.com/me/videos/", {
type: "POST",
headers: {
"Authorization": "Bearer -----",
},
data: formData,
contentType: "multipart/form-data", // changed this
dataType: "json",
crossDomain: true // for CORS policy error
}).done((response) => {
// Do something
}).fail((error) => {
// Do something
}).complete(() => {
// Do something
});
I have chaged contentType and removed mimeType. I've also removed un-necessary processData field.

How to read the POST data inside the template in JSREPORT

I have the following request to the jsreport engine:
$.ajax({
method: "POST",
contentType: "application/json",
dataType: "jsonp",
url: "http://localhost:5488/api/report",
data: {
template: {
shortid: "ry6HoQRee"
},
data: {
"D": "5"
}
},
success: function (s) {
window.open("data:application/pdf,base64," + escape(s.responseText));
},
error: function (s) {
console.log(s);
}
});
However I can't find a way to read it inside the report template:
<span>{{data.D}}</span>
How do I refer to the data object that is inside the POST body
jquery doesn't support binary responses like pdf. You should rather use XMLHttpRequest:
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://localhost:5488/api/report', true)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8')
xhr.responseType = 'arraybuffer'
xhr.onload = function(e) {
if (this.status == 200) {
window.open("data:application/pdf;base64," + window.btoa(String.fromCharCode.apply(null, new Uint8Array(xhr.response))));
}
}
xhr.send(JSON.stringify({
template: {
shortid: 'Syeopu_xe'
},
data: {
'D': '5'
}
}))
Example of reaching data using handlebars templating engine
<span>{{D}}</span>
Additionally...
You may also take a look at jsreport official browser client library. It wraps the XmlHttpRequest calls into more elegant calls:
jsreport.serverUrl = 'http://localhost:3000';
var request = {
template: {
content: 'foo', engine: 'none', recipe: 'phantom-pdf'
}
};
//display report in the new tab
jsreport.render('_blank', request);
or in async fashion
jsreport.renderAsync(request).then(function(res) {
//open in new window
window.open(res.toDataURI())
//open download dialog
res.download('test.pdf')
});