I am currently attempting to get an image upload component built in Zapier but am having issues getting it to work. I have to be able to download an image, and then POST it to a new endpoint without storing it locally. Currently, the closest I've been able to do is get an IncomingMessage to POST, but I know that's not right.
Does anyone have any advice?
let FormData = require('form-data');
let http = require('https');
const makeDownloadStream = (url) => {
new Promise((resolve, reject) => {
http.request(url, resolve).on('error', reject).end();
});
}
const makeUploadStream = (z, bundle, options) => {
var imageRequest = options;
const promise = z.request(imageRequest);
return promise.then((response) => {
return response.data;
});
}
const addAttachment = async (z, bundle) => {
/*var request = {
'url': bundle.inputData.attachment
};
const promiseAt = z.request(request);
return promiseAt.then((stream) => {*/
const form = new FormData();
var data = `{"type": "records", "attributes": {"form_id": ${bundle.inputData.form_id}}}`
const stream = await makeDownloadStream(bundle.inputData.attachment);
form.append(`field_${bundle.inputData.field_id}`, stream);
form.append('data', data);
var request = {
'url': bundle.inputData.url,
'method': 'PUT',
'headers': {
'Content-Type': `multipart/form-data; boundary=${form.getBoundary()}`
},
'body': form
};
const response = await makeUploadStream(z, bundle, request);
return response;
//});
}
I figured it out myself. For anyone needing to upload an image on Zapier, here it is:
let FormData = require('form-data');
const makeDownloadStream = (z, bundle) => {
var imageRequest = {
'url': bundle.inputData.attachment,
'method': 'GET',
'raw': true
};
const promise = z.request(imageRequest);
return promise.then(async (response) => {
var buffer = await response.buffer();
return {
'content-type': response.headers.get('content-type'),
'content': buffer,
'filename': response.headers.get('content-disposition').replace('attachment; filename="', '').replace('"', '')
}
});
}
const addAttachment = async (z, bundle) => {
const form = new FormData();
const content = await makeDownloadStream(z, bundle);
form.append(`field_${bundle.inputData.field_id}`, Buffer.from(content.content.toString('binary'), 'binary'), {
filename: content.filename
});
const request = {
'url': `${bundle.inputData.url}/api/records/${bundle.inputData.record_id}`,
'method': 'PUT',
'headers': {
'Content-Type': `multipart/form-data; boundary=${form.getBoundary()}`,
'Content-Length': form.getLengthSync()
},
'body': form
};
const promise = z.request(request);
return promise.then((response) => {
return response.data;
});
}
Related
I have the following code, where I have an array of images images and uploading each image in that array. the code is working fine, but I have an issue, where all the uploaded images have the same name ex: storage/1671621889.png.
const uploadData = async (data) => {
const attachment = []
const url = `http://127.0.0.1:8000/api/file/upload`
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
await Promise.all(images.map(async (file, index) => {
const imageData = new FormData()
imageData.append('file', file)
imageData.append('fileName', file?.name)
let result
axios.post(url, imageData, config)
.then(function(response) {
result = response.data.data.file
attachment.push(result)
})
}))
.then(() => {
submit(data, attachment)
})
}
I tried awaiting the request, but that doesn't change anything.
You're defining your upload file name already as file?.name. If you must make it unique for each request, you can simply append the index.
const uploadData = async (data) => {
const attachment = []
const url = `http://127.0.0.1:8000/api/file/upload`
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
await Promise.all(images.map(async (file, index) => {
const imageData = new FormData()
imageData.append('file', file)
imageData.append('fileName', `${file?.name}_${index}`)
let result
axios.post(url, imageData, config)
.then(function(response) {
result = response.data.data.file
attachment.push(result)
})
}))
.then(() => {
submit(data, attachment)
})
}
I got following error at file.getSignedUrl. I have other function to copy the file and create new file on Cloud Storage. Why this function need permission and where do I need to set?
Error: The caller does not have permission at Gaxios._request (/layers/google.nodejs.yarn/yarn_modules/node_modules/gaxios/build/src/gaxios.js:129:23) at runMicrotasks () at processTicksAndRejections (node:internal/process/task_queues:96:5) at async Compute.requestAsync (/layers/google.nodejs.yarn/yarn_modules/node_modules/google-auth-library/build/src/auth/oauth2client.js:368:18) at async GoogleAuth.signBlob (/layers/google.nodejs.yarn/yarn_modules/node_modules/google-auth-library/build/src/auth/googleauth.js:662:21) at async sign (/layers/google.nodejs.yarn/yarn_modules/node_modules/#google-cloud/storage/build/src/signer.js:103:35) { name: 'SigningError' }
const functions = require("firebase-functions");
const axios = require("axios");
const { Storage } = require("#google-cloud/storage");
const storage = new Storage();
// Don't forget to replace with your bucket name
const bucket = storage.bucket("projectid.appspot.com");
async function getAlbums() {
const endpoint = "https://api.mydomain.com/graphql";
const headers = {
"content-type": "application/json",
};
const graphqlQuery = {
query: `query Albums {
albums {
id
album_cover
}
}`,
};
const response = await axios({
url: endpoint,
method: "post",
headers: headers,
data: graphqlQuery,
});
if (response.errors) {
functions.logger.error("API ERROR : ", response.errors); // errors if any
} else {
return response.data.data.albums;
}
}
async function updateUrl(id, url) {
const endpoint = "https://api.mydomain.com/graphql";
const headers = {
"content-type": "application/json",
};
const graphqlQuery = {
query: `mutation UpdateAlbum($data: AlbumUpdateInput!, $where:
AlbumWhereUniqueInput!) {
updateAlbum(data: $data, where: $where) {
id
}
}`,
variables: {
data: {
album_cover: {
set: url,
},
},
where: {
id: id,
},
},
};
const response = await axios({
url: endpoint,
method: "post",
headers: headers,
data: graphqlQuery,
});
if (response.errors) {
functions.logger.error("API ERROR : ", response.errors); // errors if any
} else {
return response.data.data.album;
}
}
const triggerBucketEvent = async () => {
const config = {
action: "read",
expires: "03-17-2025",
};
const albums = await getAlbums();
albums.map((album) => {
const resizedFileName = album.id + "_300x200.webp";
const filePath = "images/albums/thumbs/" + resizedFileName;
const file = bucket.file(filePath);
functions.logger.info(file.name);
file.getSignedUrl(config, function (err, url) {
if (err) {
functions.logger.error(err);
return;
} else {
functions.logger.info(
`The signed url for ${resizedFileName} is ${url}.`
);
updateUrl(album.id, url);
}
} );
});
};
exports.updateResizedImageUrl = functions.https.onRequest(async () => {
await triggerBucketEvent();
});
I need to add Service Account Token Creator role for App Engine default service account.
I'm new to JavaScript and I'm trying make a Github API Gateway for IFTTT(cause it can't modify header) with JS on Cloudflare Worker. Here's the code:
async function handleRequest(request) {
var url = new URL(request.url)
var apiUrl = 'https://api.github.com' + url.pathname
var basicHeaders = {
'User-Agent': 'cloudflare',
'Accept': 'application/vnd.github.v3+json'
}
const { headers } = request
const contentType = headers.get('content-type')
const contentTypeUsed = !(!contentType)
if (request.method == 'POST' && contentTypeUsed) {
if (contentType.includes('application/json')) {
var body = await request.json()
if ('additionHeaders' in body) {
var additionHeaders = body.additionHeaders
delete body.additionHeaders
}
var apiRequest = {
'headers': JSON.stringify(Object.assign(basicHeaders,additionHeaders)),
'body': JSON.stringify(body),
}
} else {
return new Response('Error: Content-Type must be json', {status: 403})
}
const newRequest = new Request(apiUrl, new Request(request, apiRequest))
try {
var response = await fetch(newRequest)
return response
} catch (e) {
return new Response(JSON.stringify({error: e.message}), {status: 500})
}
} else {
var apiRequest = {
'headers': JSON.stringify(basicHeaders)
}
const newRequest = new Request(apiUrl, new Request(request, apiRequest))
var response = await fetch(newRequest)
return response
}
}
addEventListener('fetch', async (event) => {
event.respondWith(handleRequest(event.request))
})
And I got this error when I tried to run it:
Uncaught (in promise)
TypeError: Incorrect type for the 'headers' field on 'RequestInitializerDict': the provided value is not of type 'variant'.
at worker.js:1:1245
at worker.js:1:1705
Uncaught (in response)
TypeError: Incorrect type for the 'headers' field on 'RequestInitializerDict': the provided value is not of type 'variant'.
This is an older version which run well but with less flexibility:
async function handleRequest(request) {
var url = new URL(request.url)
var apiUrl = 'https://api.github.com' + url.pathname
var accessToken = 'token '
var apiRequest = {
headers: {
'User-Agent': 'cloudflare',
'Accept': 'application/vnd.github.v3+json'
}
}
const { headers } = request
const contentType = headers.get('content-type')
const contentTypeUsed = !(!contentType)
if (request.method == 'POST' && contentTypeUsed) {
if (contentType.includes('application/json')) {
var body = await request.json()
if ('token' in body) {
accessToken += body.token
delete body.token
}
var apiRequest = {
headers: {
'Authorization': accessToken,
'User-Agent': 'cloudflare',
'Accept': 'application/vnd.github.v3+json'
},
body: JSON.stringify(body),
}
} else {
return new Response('Error: Content-Type must be json', {status: 403})
}
const newRequest = new Request(apiUrl, new Request(request, apiRequest))
try {
var response = await fetch(newRequest)
return response
} catch (e) {
return new Response(JSON.stringify({error: e.message}), {status: 500})
}
} else {
const newRequest = new Request(apiUrl, new Request(request, apiRequest))
var response = await fetch(newRequest)
return response
}
}
addEventListener('fetch', async (event) => {
event.respondWith(handleRequest(event.request))
})
The only difference seems to be apiRequest, but I don't know how to fix it. I tried to claim the variable with var apiRequest = new Object() first but didn't work.
Fix with this:
let apiRequest = new Object
apiRequest.headers = Object.assign(basicHeaders, additionHeaders)
apiRequest.body = JSON.stringify(body)
And the apiRequest will look like this:
{headers:{},body:"{}"}
This seems like what RequestInitializerDict want.
Hello after setup a simple async function with promise return i'd like to use then promise instead of try!
But is returning
await is a reserved word
for the second await in the function.
i've tried to place async return promise the data! but did not worked either
async infiniteNotification(page = 1) {
let page = this.state.page;
console.log("^^^^^", page);
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch(`/notifications?page=${page}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
params: { page }
})
.then(data => data.json())
.then(data => {
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
fetch("/notifications/mark_as_read", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Access: auth_token
},
body: JSON.stringify({
notification: {
read: true
}
})
}).then(response => {
this.props.changeNotifications();
});
})
.catch(err => {
console.log(err);
});
}
> await is a reserved word (100:25)
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
^
fetch("/notifications/mark_as_read", {
You should refactor how you make your requests. I would have a common function to handle setting up the request and everything.
const makeRequest = async (url, options, auth_token) => {
try {
// Default options and request method
if (!options) options = {}
options.method = options.method || 'GET'
// always pass a body through, handle the payload here
if (options.body && (options.method === 'POST' || options.method === 'PUT')) {
options.body = JSON.stringify(options.body)
} else if (options.body) {
url = appendQueryString(url, options.body)
delete options.body
}
// setup headers
if (!options.headers) options.headers = {}
const headers = new Headers()
for(const key of Object.keys(options.headers)) {
headers.append(key, (options.headers as any)[key])
}
if (auth_token) {
headers.append('Access', auth_token)
}
headers.append('Accept', 'application/json')
headers.append('Content-Type', 'application/json')
options.headers = headers
const response = await fetch(url, options as any)
const json = await response.json()
if (!response.ok) {
throw json
}
return json
} catch (e) {
console.error(e)
throw e
}
}
appendQueryString is a little helper util to do the get qs params in the url
const appendQueryString = (urlPath, params) => {
const searchParams = new URLSearchParams()
for (const key of Object.keys(params)) {
searchParams.append(key, params[key])
}
return `${urlPath}?${searchParams.toString()}`
}
Now, to get to how you update your code, you'll notice things become less verbose and more extensive.
async infiniteNotification(page = 1) {
try {
let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);
const data = await makeRequest(
`/notifications`,
{ body: { page } },
auth_token
)
var allData = this.state.notifications.concat(data.notifications);
this.setState({
notifications: allData,
page: this.state.page + 1,
});
const markedAsReadResponse = makeRequest(
"/notifications/mark_as_read",
{
method: "POST",
body: {
notification: { read: true }
},
auth_token
)
this.props.changeNotifications();
} catch (e) {
// TODO handle your errors
}
}
I am trying to send form data of the updated user details to the back end which node server in angular 2,However I couldn't send the form data and the server responds with status of 500,In angularjs I have done something like this,
service file
update: {
method: 'POST',
params: {
dest1: 'update'
},
transformRequest: angular.identity,
'headers': {
'Content-Type': undefined
}
}
In controller as
var fd = new FormData();
var user = {
_id: StorageFactory.getUserDetail()._id,
loc: locDetails
};
fd.append('user', angular.toJson(user));
UserService.update(fd).
$promise.then(
function(value) {
console.info(value);
updateUserDetailsInStorage();
},
function(err) {
console.error(err);
}
);
I couldn't to figure how to do this in angular 2 as angular.toJson,angular.identity and transformrequest features are not available in angular 2,
so far I have done the following in angular 2,
let fd = new FormData();
let user = {
_id: this.appManager.getUserDetail()._id,
loc: locDetails
};
fd.append('user', JSON.stringify(user));
this.userService.update(fd).subscribe((value) => {
console.log(value);
this.updateUserDetailsInStorage();
}, (err) => {
console.error(err);
});
http service file
update(body) {
console.log('update', body);
const headers = new Headers({
'Content-Type': undefined
});
const options = new RequestOptions({
headers: headers
});
return this.http.post(`${app.DOMAIN}` + 'user/update', body, options)
.map((res: Response) => {
res.json();
}).do(data => {
console.log('response', data);
})
}
I have read many posts and tried few things but so far it was unsuccessful, could anyone suggest me how to do this?
You can add headers if your server controller requires it else you can simply post it like this
let body = new FormData();
body.append('email', 'emailId');
body.append('password', 'xyz');
this.http.post(url, body);
This is a functional solution for build a POST request in Angular2, you don't need an Authorization header.
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
var body = "firstname=" + user.firstname + "&lastname=" + user.lastname + "&username=" + user.username + "&email=" + user.email + "&password=" + user.password;
return new Promise((resolve) => {
this.http.post("http://XXXXXXXXXXX/users/create", body, options).subscribe((data) => {
if (data.json()) {
resolve(data.json());
} else {
console.log("Error");
}
}
)
});
Here is the method I've used in angular 4 for uploading files....
for Ui
<input type="file"id="file"(change)="handleFileInput($event)">
and .ts file I've added this ....
handleFileInput(event) {
let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
let files: FileList = target.files;
this.fileToUpload = files[0];
console.log(this.fileToUpload);
}
uploadFileToActivity() {
console.log('Uploading file in process...!' + this.fileToUpload );
this.fontService.upload(this.fileToUpload).subscribe(
success => {
console.log(JSON.stringify(this.fileToUpload));
console.log('Uploading file succefully...!');
console.log('Uploading file succefully...!' + JSON.stringify(success));
},
err => console.log(err),
);
}
and In services
upload(fileToUpload: File) {
const headers = new Headers({'enctype': 'multipart/form-data'});
// headers.append('Accept', 'application/json');
const options = new RequestOptions({headers: headers});
const formData: FormData = new FormData();
formData.append('file', fileToUpload, fileToUpload.name);
console.log('before hist the service' + formData);
return this.http
.post(`${this.appSettings.baseUrl}/Containers/avatar/upload/`, formData , options).map(
res => {
const data = res.json();
return data;
}
).catch(this.handleError);
}
This method used for single file uploading to the server directory.
Here is the method from my app which works fine.
updateProfileInformation(user: User) {
this.userSettings.firstName = user.firstName;
this.userSettings.lastName = user.lastName;
this.userSettings.dob = user.dob;
var headers = new Headers();
headers.append('Content-Type', this.constants.jsonContentType);
var s = localStorage.getItem("accessToken");
headers.append("Authorization", "Bearer " + s);
var body = JSON.stringify(this.userSettings);
return this.http.post(this.constants.userUrl + "UpdateUser", body, { headers: headers })
.map((response: Response) => {
var result = response.json();
return result;
})
.catch(this.handleError)
}
FINAL answer
sending like below working fine .
const input = new FormData();
input['payload'] = JSON.stringify(param);
console.log(input);
alert(input);
return this.httpClient.post(this.hostnameService.razor + 'pipelines/' +
workflowId, input).subscribe(value => {
console.log('response for Manual Pipeline ' + value);
return value;
}, err => {
console.log(err);
});