How to attach blob index tags during a Azure Blob put request? - azure

I followed azure documentation https://learn.microsoft.com/en-us/rest/api/storageservices/put-blob for adding tags during the objects creation in azure blob. Its says that, we have to add 'x-ms-tags' in the request headers. The header that I am attaching to the PUT request is,
headers: {
'Content-Type': file.type,
'x-ms-blob-type': 'BlockBlob',
'x-ms-tags': 'tag1=value1'
}
But these tags are not getting added to the actual blobs. What am i missing here?
Also in the documentaion, it says that 'x-ms-tags' is "Supported in version 2019-12-12 and newer.". Which version they are mentioning here?
Edit1:
Code for uploading the file:
uploadToAzure = function (public_url, sas_token, file) {
return $http({
method: 'PUT',
url: public_url + '?' + sas_token,
ignoreLoadingBar: true,
data: file,
headers: {
'Content-Type': file.type,
'x-ms-blob-type': 'BlockBlob',
'x-ms-tags': 'tag1=value1'
}
})
.then(function (response) {
return response;
}, function (error) {
console.error("error", error)
return error;
});
}
Edit 2:
Edit 2:
Backend code for generating token:
GEM:
gem 'azure-storage-blob'
azure_blob_storage_initializer.rb
AZURE_SAS_TOKEN_GENERATOR = Azure::Storage::Common::Core::Auth::SharedAccessSignature.new(
ENV['AZURE_BLOB_STORAGE_ACCOUNT_NAME'],
ENV['AZURE_BLOB_STORAGE_ACCESS_KEY']
)
Generating token login:
SAS_TOKEN_OPTIONS = { service: 'b', resource: 'b' }.freeze
sas_token = AZURE_SAS_TOKEN_GENERATOR.generate_service_sas_token(blob_path, SAS_TOKEN_OPTIONS.merge(permissions: 'w'))

Related

ReCAPTCHA siteverify not returning JSON response

I am implementing recaptcha into a user submittable form. After attempting to validate the token using the url
https://www.google.com/recaptcha/api/siteverify
The response given is something similar to
▼���RPP*.MNN-.V�RHK�)N�☺��▬§�↨�&秤�ģ�B#�̼�Ĝ�¶�̼��↕ݢ�����T%�d,W-�
� K
The code used to attempt to validate the response is as follows
var data = JSON.stringify({
secret: process.env.RECAPTCHA_SECRET,
response: req.body.gcaptcha_response,
});
var config = {
method: "post",
url: "https://www.google.com/recaptcha/api/siteverify",
headers: {
"Content-Type": "application/json",
},
data: data,
};
axios(config)
.then(function (response) {
res.json({
success: true,
body: response.data,
});
})
.catch(function (error) {
console.log(error);
});
I have also attempted with other content types to no success. I have also attempted to follow the answer given in this thread
This is a workaround for now
I just realised this is happening for the latest version of axios.
If you install axios version 1.1 it returns the data as json.
Thread: https://github.com/axios/axios/issues/5298

return file id after resumable upload finished with google drive

I'm integrating google drive API in my application and I'm using resumable upload approach
but i can't figure out how can i get file id after upload finished in the resumable response body
here is my code to get resumable uri
const body = JSON.stringify({
name:file.originalname,
mimeType:file.mimetype,
parents:[parent folder id]
})
const url = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable'
const option = {
method: 'post',
body,
headers: {
Authorization: `Bearer ${access_token}`,
'Content-Type': 'application/json; charset=UTF-8',
}
}
const response = await fetch(url, option)
const resumableURI = response.headers.get('location')
and this is my code to upload my file chunks
const options = {
method: 'PUT',
headers: {
'Content-Length': file.size,
'Content-Range': `bytes ${start}-${end - 1}/${length}`,
},
body: file.buffer, // contents of the chunk
};
const response = await fetch(RESUBMALEURI, options)
this is the response i got from api after upload complete
response: Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
[Symbol(Response internals)]: {
url: 'https://www.googleapis.com/upload/drive/v3/files?
uploadType=resumable&upload_id=ADPycdvajyaSOgYUjPmFgZIbi-
vbjM0U7xHe0yLy1eahXOC1Zq06K7ZFN2O0c_IKRdEJfa-WFc8DwE814cjV0nhCv0U',
status: 200,
statusText: 'OK',
headers: [Headers],
counter: 0
}
}
}
is there any option i can add to request of resubmale uri or upload request itself to return the file id in the end
When I saw your script and your additional response value, I'm worried that you might have retrieved the response value using console.log(response) from const response = await fetch(RESUBMALEURI, options). If my understanding is correct, in that case, unfortunately, such a response is obtained.
If your script for the resumable upload the file works fine and the upload is completely finished, how about the following modification?
From:
const response = await fetch(RESUBMALEURI, options)
To:
const response = await fetch(RESUBMALEURI, options)
const res = await response.json();
console.log(res);
// console.log(res.id); // If you want to retrieve only the file ID, you can use this.
By this modification, when at the last request, you can obtain the following value.
{
kind: 'drive#file',
id: '###',
name: '###',
mimeType: '###'
}
Note:
By the way, in your 1st request, the location is put in the variable of resumableURI. But in your script for uploading the file content, you are using the RESUBMALEURI as the endpoint. If your actual situation uses this, please modify this. Please be careful about this.
Reference:
node-fetch

Must provide HTTP header "Authorization" or URL parameter "authorization"

I am trying to download a File from dropbox using Dropbox APIs. I use the code below
axios.post('https://content.dropboxapi.com/2/files/download', {
method: 'POST',
headers: {
Authorization: 'Bearer ${MY token}',
'Dropbox-API-Arg': { path: '/Thillai Maharajan.jpg' }
}
})
.then(function (response) {
console.log("RESPONSE: ",response.data);
})
.catch(function (error) {
console.log("ERROR RES",error);
});
But it says data: 'Error in call to API function "files/download": Must provide HTTP header "Authorization" or URL parameter "authorization".'
Can anyone help?
You can refer the Dropbox API Document at https://www.dropbox.com/developers/documentation/http/documentation#files-download
I just got the answer. I have to Stringify the Dropbox-API-Arg Parameter using JSON.stringify(). Because The header argument could not be a JSON. I changed that and it worked.
'Dropbox-API-Arg' : JSON.stringify({"path":"/Thillai Maharajan.jpg"})

Updating metadata file in sharepoint online via REST API

I upload a file to sharepoint and trying to update its metadata, but I always get error 400 in last step.
As far as I understand, sharepoint only handles lists and items. A "folder" is a list and both metadata and files inside are items. And a "file" is a list and its metadata are items.
Documentation about updating metadata say about to make a POST request to:
https: // {site_url} / _api / web / lists / GetByTitle ('{list_title}') / items ({item_id})
Updating files must be done by PUT method (not MERGE allowed), but updating metadata must be done specifically by MERGE method. I have tried both, and both failed.
This is my current updating metadata request, but I'm continuing getting an error 400.
var data = {
"__metadata": {
"type":type
},
"Description":"lorem ipsum"
};
var headerToken = {
headers: {
'Authorization':'Bearer ' + token
, 'X-HTTP-Method':'MERGE'
, 'Accept':'application/json;odata=verbose'
, 'Content-Type':'application/json;odata=verbose'
, 'Content-Length':JSON.stringify(data).length
, 'If-Match': etag
, 'X-RequestDigest': digest
}
};
try {
var response = await axios.post(
'https://{site_url}/_api/web/lists/GetByTitle("'+MY_FOLDER+'")/items('+id+')'
, JSON.stringify(data)
, headerToken
);
return response;
}
type, etag and id are get from uploading file response and digest is get from a request to contextinfo endpoint. MY_FOLDER is a test library and at this moment is a constant.
You need to use single quotes in getbytitle.
"https://{site_url}/_api/web/lists/GetByTitle('"+MY_FOLDER+"')/items("+id+")"
Updated:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
UpdateFolder()
function UpdateFolder(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Doc')/items(30)",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose",
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
},
data: "{__metadata:{'type':'SP.Data.DocItem'},test:'test'}",
/*where Title is column name and add your desired new data*/
success: function(data) {
console.log(data);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
})
</script>

Problem setting the name of a file when using the Google Drive REST API for resumable uploads

async function createResumableSession(filePath, authClient){
try {
const fileStats = await statsAsync(filePath);
const fileSize = fileStats.size;
const postResult = await new Promise((resolve, reject)=>{
request({
method: 'post',
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
followAllRedirects: true,
headers: {
Authorization: "Bearer " + authClient.credentials.access_token,
"X-Upload-Content-Length": `${fileSize}`,
"Content-Length": "0",
"Content-Type": "application/json; charset=UTF-8"
},
body:JSON.stringify({
title: "myfile.backup"
})
}, function (error, response) {
if (error)
return reject(error);
resolve({
statusCode: response.statusCode,
location: response.headers.location,
body: response.body
});
})
})
return {
postResult,
fileSize
}
} catch (error) {
throw error;
}
}
I have this function to create a resumable upload on the Google Drive API, its creating the session correctly but I cant set the file name, after the upload is completed the file name always end as "untitled"
How about this modification?
Modification points:
In your script, from the endpoint of https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable, it is found that you are using Drive API v3. In this case, in order to set the filename, it is required to use the property of name. In your script, title is used. In this case, it is for Drive API v2. So please modify as follows.
Modified script:
Please modify your script as follows.
From:
title: "myfile.backup"
To:
name: "myfile.backup"
Reference:
Files: create
If this was not the direct solution of your issue, I apologize.
Added:
As a simple sample script, I added a sample script. In this sample script, a text file is uploaded using the resumable upload. In this case, the file is uploaded as the filename of "sample". And you can see the text of foo in the uploaded file.
Sample script:
const request = require('request');
const accessToken = "###"; // Please set your access token.
request({
method: 'POST',
url: 'https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable',
headers: {
"Authorization": `Bearer ${accessToken}`,
"Content-Type": "application/json"
},
body: JSON.stringify({name: "sample", mimeType: "text/plain"})
}, (err, res) => {
if (err) {
console.log(err);
return;
}
request({
method: 'PUT',
url: res.headers.location,
headers: {"Content-Range": "bytes 0-2/3"},
body: Buffer.from("foo")
}, (err, res) => {
if (err) {
console.log(err);
return;
}
console.log(res.statusCode)
console.log(res.body)
});
});
Using the property of name, the metadata of file has the filename of sample.
But unfortunately, from your replying, I cannot understand about your current issue. So can I ask you about the detail information about the problem persists? And in order to correctly understand about your situation, can you provide the detail flow and whole script for replicating your issue? Of course, please remove your personal information. By this, I would like to confirm it. If you can cooperate to resolve your issue, I'm glad.

Resources