Problems uploading jpg with OneDrive Rest Api - rest

For this HTML5 phone App I have to use the OneDrive REST API.
I managed to upload the file, but the file up on the server is not in .jpg format and won't display in a jpg viewer. After logging in through the REST API and getting a token back, I used XMLHttpRequest to PUT the file. I've tried passing it up as an ArrayBuffer and as a base64 encoded string. In each case the file makes it there, but is not decoded properly. I figured I needed to tell the webserver how to decode the file with "request.setRequestHeader('Content-Type', 'image/jpg')" ,but I get back the following error message from the OneDrive server:
"error": {
"code": "request_body_invalid_media_type",
"message": "The Content-Type header 'text/plain' isn't supported."
}
this.uploadFile = function (token, fileUri,fileName, fileTools, success, fail) {
var me = app.log('||Microsoft.uploadFile||');
fileTools.readFileContent(fileUri, 'dataUrl', gotData, fileError);
function fileError(err) {
app.logError(me + '::fileError:::' + err);
}
function gotData(base64String) {
var request = new XMLHttpRequest;
app.log(me + '::token::' + token);
request.open("PUT", "https://apis.live.net/v5.0/me/skydrive/files/" + fileName + "?access_token=" + token, true);
request.setRequestHeader('Content-Type', 'text/plain');
//request.setRequestHeader('Content-Type', 'image/jpg');
//request.setRequestHeader('Content-Transfer-Encoding', 'base64;charset=utf-8');
request.onload = function (e) {
app.log(request.responseText);
success(e);
};
request.onerror = function (e) {
app.log(me + '::7::');
fail(e.error.message);
};
app.log(me + '::8::' + base64String.substr(0,100));
var b = new Base64Stuff();
var aBuffer = b.base64ToBuffer(b.removeBase64jpgHeader(base64String));
request.send(aBuffer);
//request.send(base64String);
}
}

try
request.setRequestHeader('Content-Type', '');

Related

Firebase hosting file upload via REST with Apps Script

I want to upload a file to Firebase hosting file upload via REST with Apps Script. Been trying to find a solution for days to no avail :( would highly appreciate any recommendations.
I'm following the official documentation here:
https://firebase.google.com/docs/reference/hosting/rest/v1beta1/sites.versions/populateFiles
And I can successfully get the upload URL using this code:
function getUploadURL() {
const YOUR_PROJECT_ID = 'sites/url-shortener-e42ec/versions/dd393a80797d713d';
let postUrl = 'https://firebasehosting.googleapis.com/v1beta1/YOUR_PROJECT_ID:populateFiles';
postUrl = postUrl.replace('YOUR_PROJECT_ID', YOUR_PROJECT_ID);
const options = {
method: 'post',
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
},
muteHttpExceptions: true
};
const response = UrlFetchApp.fetch(postUrl, options);
Logger.log(response);
}
which returns the following:
{
"uploadUrl": "https://upload-firebasehosting.googleapis.com/upload/sites/url-shortener-e42ec/versions/dd393a80797d713d/files"
}
And this is where I get kinda lost because I'm not quite sure on what to do next. The documentation says:
map (key: string, value: string)
A set of file paths to the hashes corresponding to assets that should be added to the version.
A file path to an empty hash will remove the path from the version.
Calculate a hash by Gzipping the file then taking the SHA256 hash of the newly compressed file.
But if I add a payload with a file hash to the call like so:
{
"files": {
"/teste": "3f0749957a1c4d91ed18b8e9df122709974e4e9c94c57f9245794c21dd76d4bd"
}
}
...then I get the error:
{
"error": {
"code": 400,
"message": "Precondition check failed.",
"status": "FAILED_PRECONDITION"
}
}
PART 2 :
The next issue I found is, now that I have the upload URL, I will need to actually upload the file, and according to their documentation I should:
Perform a multipart POST of the Gzipped file contents to the URL using a forward slash and the hash of the file appended to the end.
which I tried with the following apps script code:
function convert(hash) {
return hash.map(byte => ('0' + (byte & 0xFF).toString(16)).slice(-2)).join('');
}
function postFile() {
var files = DriveApp.getFilesByName('abc.txt');
let gzip;
let hash;
if (files.hasNext()) {
var file = files.next();
gzip = Utilities.gzip(file.getBlob());
hash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, gzip.getBytes());
}
let postUrl = 'https://upload-firebasehosting.googleapis.com/upload/sites/url-shortener-e42ec/versions/dd393a80797d713d/files/' + convert(hash);
/*
var textBlob = Utilities.newBlob("abc");
const gzip = Utilities.gzip(textBlob);
const hash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, gzipFile.getBytes());
*/
const data = {
"files": {
"/test.txt": convert(hash)
}
};
const options = {
method: 'post',
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
accept: 'application/json',
contentType: 'application/json'
},
muteHttpExceptions: true,
payload: JSON.stringify(data)
};
const response = UrlFetchApp.fetch(postUrl, options);
Logger.log(response);
}
... and get the following error:
Couldn't process request (status=412): File url-shortener-e42ec/dd393a80797d713d/0b3b82379e00a1994a46452e8cfd8b2c43ee8599f169a9ee4176253f1a8de469 can't be uploaded.
Appreciate all the help I can get. Thanks in advance!

Upload a file with google drive rest api

I am using a service account in google apps script so i can not use the normal google apps script api.
So i use the drive rest api for creating, moving, copy etc. but i am able to upload a file with the rest api. It uploads a file but it is without content or with wrong content.
This is my code:
var contentType = data.substring(5, data.indexOf(';')),
bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,') + 7)),
blob = Utilities.newBlob(bytes, contentType, file);
var service = getService();
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media';
var data = {
name: name,
mimeType: "application/pdf",
parents: [parent]
};
var options = {
method: 'post',
contentType: 'application/json',
body: blob ,
payload: JSON.stringify(data),
muteHttpExceptions: true,
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.stringify(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
return result["id"];
} else {
Logger.log(service.getLastError());
}
Thanks
When uploading files using Drive API, you need to use the files.create method. You can see the javascript code reference in Basic uploads where it is used. Also note that the App Script uploading files uses the Drive v2 version of files.insert instead of files.create.

Make dropzone.js do a raw upload

I like to use dropzone.js for file upload to a REST-like server. While dropzone.js can switch the request method to PUT, it still sends something like a mulitpart file upload. My server expects raw data as body for the a single ressource PUT method, so the files uploaded will have multipart seperators included.
How can I tell dropzone.js to put the raw data into the request body, no more no less?
Please refer this answer that I wrote: https://stackoverflow.com/a/38734015/3746828
Add below options, then working.
myDropzone.options.sending = function(file, xhr) {
var _send = xhr.send;
xhr.send = function() {
_send.call(xhr, file);
}
}
Below is another method that patches xhr with a params function passed in as an option to Dropzone. This method will also work for chunked files. The chunked execution path below also adds the headers required for a resumable file upload using the OneDrive API as documented here: https://learn.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession?view=odsp-graph-online
const CHUNK_SIZE=10485760 //10MiB
Dropzone.options.dropzone = {
method: "put",
headers: {
'Cache-Control': null,
'X-Requested-With': null
},
filesizeBase: 1024,
maxFilesize: 102400, // 100G in MB, max onedrive filesize
chunking: true,
chunkSize: CHUNK_SIZE,
params: function(files, xhr, chunk) {
if (chunk) {
const chunk_start = (chunk.index * CHUNK_SIZE)
xhr.setRequestHeader('Content-Range',
'bytes ' + chunk_start
+ '-' + (chunk_start + chunk.dataBlock.data.size - 1)
+ '/' + files[0].size)
var _send = xhr.send
xhr.send = function() {
_send.call(xhr, chunk.dataBlock.data)
}
} else {
var _send = xhr.send
xhr.send = function() {
_send.call(xhr, files[0])
}
}
}
}

Sails.js checking stuff before uploading files to MongoDB with skipper (valid files, image resizing etc)

I'm currently creating a file upload system in my application. My backend is Sails.js (10.4), which serves as an API for my separate front-end (Angular).
I've chosen to store the files I'm uploading to my MongoDB instance, and using sails' build in file upload module Skipper. I'm using the adapter skipper-gridfs (https://github.com/willhuang85/skipper-gridfs) to upload the files to mongo.
Now, it's not a problem to upload the files themselves: I'm using dropzone.js on my client, which sends the uploaded files to /api/v1/files/upload. The files will get uploaded.
To achieve this i'm using the following code in my FileController:
module.exports = {
upload: function(req, res) {
req.file('uploadfile').upload({
// ...any other options here...
adapter: require('skipper-gridfs'),
uri: 'mongodb://localhost:27017/db_name.files'
}, function(err, files) {
if (err) {
return res.serverError(err);
}
console.log('', files);
return res.json({
message: files.length + ' file(s) uploaded successfully!',
files: files
});
});
}
};
Now the problem: I want to do stuff with the files before they get uploaded. Specifically two things:
Check if the file is allowed: does the content-type header match the file types I want to allow? (jpeg, png, pdf etc. - just basic files).
If the file is an image, resize it to a few pre-defined sizes using imagemagick (or something similar).
Add file-specific information that will also be saved to the database: a reference to the user who has uploaded the file, and a reference to the model (i.e. article/comment) the file is part of.
I don't have a clue where to start or how to implement this kind of functionality. So any help would be greatly appreciated!
Ok, after fiddling with this for a while I've managed to find a way that seems to work.
It could probably be better, but it does what I want it to do for now:
upload: function(req, res) {
var upload = req.file('file')._files[0].stream,
headers = upload.headers,
byteCount = upload.byteCount,
validated = true,
errorMessages = [],
fileParams = {},
settings = {
allowedTypes: ['image/jpeg', 'image/png'],
maxBytes: 100 * 1024 * 1024
};
// Check file type
if (_.indexOf(settings.allowedTypes, headers['content-type']) === -1) {
validated = false;
errorMessages.push('Wrong filetype (' + headers['content-type'] + ').');
}
// Check file size
if (byteCount > settings.maxBytes) {
validated = false;
errorMessages.push('Filesize exceeded: ' + byteCount + '/' + settings.maxBytes + '.');
}
// Upload the file.
if (validated) {
sails.log.verbose(__filename + ':' + __line + ' [File validated: starting upload.]');
// First upload the file
req.file('file').upload({}, function(err, files) {
if (err) {
return res.serverError(err);
}
fileParams = {
fileName: files[0].fd.split('/').pop().split('.').shift(),
extension: files[0].fd.split('.').pop(),
originalName: upload.filename,
contentType: files[0].type,
fileSize: files[0].size,
uploadedBy: req.userID
};
// Create a File model.
File.create(fileParams, function(err, newFile) {
if (err) {
return res.serverError(err);
}
return res.json(200, {
message: files.length + ' file(s) uploaded successfully!',
file: newFile
});
});
});
} else {
sails.log.verbose(__filename + ':' + __line + ' [File not uploaded: ', errorMessages.join(' - ') + ']');
return res.json(400, {
message: 'File not uploaded: ' + errorMessages.join(' - ')
});
}
},
Instead of using skipper-gridfs i've chosen to use local file storage, but the idea stays the same. Again, it's not as complete as it should be yet, but it's an easy way to validate simple stuff like filetype and size. If somebody has a better solution, please post it :)!
You can specify a callback for the .upload() function. Example:
req.file('media').upload(function (error, files) {
var file;
// Make sure upload succeeded.
if (error) {
return res.serverError('upload_failed', error);
}
// files is an array of files with the properties you want, like files[0].size
}
You can call the adapter, with the file to upload from there, within the callback of .upload().

Photo upload with facebook-node-sdk Module / (#324) Requires upload file

I'm trying to send a photo using facebook node sdk module to a page. https://github.com/Thuzi/facebook-node-sdk/
I'm able to post to the page wall or to uplaod from an url. But i have a problem trying to uplaod photo from data.
That is how i connected :
FB.api('oauth/access_token', {
client_id: clientid,
client_secret: clientsecret,
redirect_uri: redirecturi,
code: code,
scope: scope,
fileUpload : true,
}, function (resf) { ...}
I get the good access token like this :
FB.api('/me/accounts', function (resf) {
if (!resf || resf.error) {
console.log(!resf ? 'error occurred' : resf.error);
return;
}
for (var i = 0; i < resf.data.length; i++) {
if (resf.data[i].id == pageid)
{
resf.data[i]. access_token
}
});
And i try to upload the photo :
var buff = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBg8SEBQQEBQUEBQUFRQVERYUFhMYGBYVFBUVFBUVEhQYHCYgFxkkGhUVHy8gIycpLSwuFR4xNTAqNSYtLCkBCQoKDgwOFw8PFzUcHSQwKS01NTUsNTUpNS8sNCwsKS4pNDUuLTUsLC8pLCwpNTUvNSkpNSkvLCwsKikpKSksNv/AABEIAK8BHwMBIgACEQEDEQH/xAAcAAEAAgIDAQAAAAAAAAAAAAAABwgFBgEDBAL/xABKEAABAwICBgYECgULBQAAAAABAAIDBBEFIQYHEjFBcRMiUWGBsTI0kaEjQlJyc3SCkrKzCBQkYsEVFhczNVNUVZPR0mODoqPC/8QAGwEBAQADAQEBAAAAAAAAAAAAAAECAwUEBgf/xAAoEQEAAgIBAwIFBQAAAAAAAAAAAQIDEQQFEiExcRMyQZHRUYGh8PH/2gAMAwEAAhEDEQA/AJxREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQdFbWxQxulme2NjRdznkBoG65J3LtjkDgHNIIIBBG4g5ghaJrtxMRYRLH8adzI2j7XSO9zD7Vt2CuApYScgIY7/cag96LScX1p0sTiyFjqi29wIazwcczzsvLh+tuFzgJoXRA/Ga4PA5iwPsWv4tN626MdL5dqd8Y51/P29UgIumkrI5WNkicHscLtc03BC7lsc+YmJ1IiIiCIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAuCV8VFQxjS+RwY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6kq+pmM+IVzXvd6RY1z3ZbgC7ZDQOwCyCG1J+rbVLLUPbVVzDHALOZE4EOm4jaG9sfPN3LNSRozqrw2iIe2Pp5Rukms4g9rG22W8wL963BF24a0AWGQG5coiIIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiICIiAiIgIiIP/Z";
var body = 'My firstdfsfsfd';
FB.api(pageid + '/photos', 'post', { message: body, source: buff, }, function (resf) {
if (!resf || resf.error) {
console.log(!resf ? 'error occurred' : resf.error);
return;
}
console.log( resf);
res.send(resf);
});
And i have this error :
{
"error": {
"message": "(#324) Requires upload file",
"type": "OAuthException",
"code": 324
}
}
This call is working :
var body = 'My firstdfsfsfd';
FB.api(pageid + '/photos', 'post', { message: body, url: 'url_image', }, function (resf) {
if (!resf || resf.error) {
console.log(!resf ? 'error occurred' : resf.error);
return;
}
console.log( resf);
res.send(resf);
});
What did i forget ?
Does multipart upload is allowing with this module : https://github.com/Thuzi/facebook-node-sdk/
It does not appear to support multipart. You could do it manually with the request module:
var request = require('request');
// ....
var access_token = 'abc123',
pageid = 'me',
fburl = 'https://graph.facebook.com/'
+ pageid
+ '/photos?access_token='
+ access_token,
req,
form;
req = request.post(fburl, function(err, res, body) {
if (err)
return console.error('Upload failed:', err);
console.log('Upload successful! Server responded with:', body);
});
form = req.form()
// append a normal literal text field ...
form.append('message', 'My photo!');
// append a file field by streaming a file from disk ...
form.append('source', fs.createReadStream(path.join(__dirname, 'photo.jpg')));
// or append a Buffer ...
form.append('source', someBuffer);
// or append the contents of a remote url ...
form.append('source', request('http://google.com/doodle.png'));
Example (from mscdex) above works for:
form.append('source', requestLib('<imageURL>'));
Gives response:
{"id":"756317401077924","post_id":"100000990137087_756310827745248"}
Also works for:
form.append('source', fs.createReadStream('<imagepath>'));
Gives response:
{"id":"756328687743462","post_id":"100000990137087_756310827745248"}
This is probably all I need. Thanks mscdex, very helpful. But out of curiosity, when I replaced it with an image buffer:
form.append('source', imageBuffer);
It gives the same error as OP (even when using the same image string as OP):
{"error":{"message":"(#324) Requires upload file","type":"OAuthException","code":324}}
Why? My guess is Facebook wants a specific format for an encoded image.