Nuxt3 and Cloudinary Upload API: The "path" argument must be of type string. Received an instance of Object - cloudinary

I am trying to use the Cloudinary Upload API to programmatically upload a File object to my Cloudinary media library, but for some reason I get the following server error:
{
"url": "/api/cloudinary/upload",
"statusCode": 500,
"statusMessage": "Internal Server Error",
"message": "The \"path\" argument must be of type string. Received an instance of Object",
"description": "<pre><span class=\"stack internal\">at new NodeError (node:internal/errors:371:5)</span>\n<span class=\"stack internal\">at validateString (node:internal/validators:119:11)</span>\n<span class=\"stack\">at basename (node:path:752:5)</span>\n<span class=\"stack internal\">at post // snipped out rest
Am I not setting up the folder path correctly here or is something else the problem?
I am using the following code (in my NuxtJS app):
components/UserProfileAvatar.vue:
const file = ref(null)
const handleAvatarUpload = async (e) => {
file.value = e.target.files[0]
// Upload file to Cloudinary and get public_id
const options = {
public_id: 'profile-image',
folder: `users/${userStore.userProfile.uid}/avatar/`
}
try {
const response = await $fetch('/api/cloudinary/upload', {
method: 'POST',
body: {
options: options,
file: file.value
}
})
console.log('Uploaded!', response.asset)
} catch (error) {
console.log('Error uploading file', error)
}
}
If I console log the logic above, I get the following output:
Anyone spot anything as to why I get the the error "The Path argument must be of type string. Received an instance of Object" in my original attempt?

Related

Error while uploading Multiple Files with different File Names With Skipper in Sails Js

I am trying to upload multiple type of files to S3 in sails js
Files are as Follow : VehicleImages, VehicleVideos, VehicleDocuments
I am passing these three type of files with attribute name with same name as these files to my server via multipart/form-data
My approach is to upload one type of file lets say VehicleImages by using await
Then upload the next and then the next.
I am unable to do so since i get the error :
{
"cause": {
"code": "EMAXBUFFER",
"message": "EMAXBUFFER: An upstream (`vehicleDocuments`) timed out before it was
plugged into a receiver. It was still unused after waiting 4500ms.
You can configure this timeout by changing the `maxTimeToBuffer`
option.\n\nNote that this error might be occurring due to an earlier
file upload that is finally timing out after an unrelated server
error."
},
"isOperational": true,
"code": "EMAXBUFFER"
}
This is my code for policies folder
VehicleController: {
create: ["isLoggedIn", "vehicleImages", "vehicleKey", "vehicleDocuments"],
update: ["isLoggedIn", "vehicleImages", "vehicleKey", "vehicleDocuments"],
"*": "isLoggedIn",
},
This is the helper function that i am using in my policies
fn: async function (inputs) {
const { req, res, proceed, fieldName, folderName, setParams } = inputs;
const skipperUpstream = req.file(fieldName);
const file = skipperUpstream._files[0];
if (!file) {
// `skipperUpstream.__proto__` is `Upstream`. It provides `noMoreFiles()` to stop receiving files.
// It also clears all timeouts: https://npmdoc.github.io/node-npmdoc-skipper/build/apidoc.html#apidoc.element.skipper.Upstream.prototype.noMoreFiles
skipperUpstream.noMoreFiles();
return proceed();
}
let timestamp = Date.now();
let uploadedFiles = await sails.upload(req.file(fieldName), {
adapter: require("skipper-s3"),
key: process.env.AWS_ACCESS_KEY_ID,
secret: process.env.AWS_SECRET_ACCESS_KEY,
bucket: process.env.AWS_BUCKET_NAME,
region: "us-east-2",
headers: {
"x-amz-acl": "public-read",
},
// maxBytes: sails.config.custom.maxFileSize,
// change folder and file name
dirname: folderName,
saveAs: function (__newFileStream, next) {
next(undefined, timestamp + __newFileStream.filename);
},
});
sails.log("filesUploaded In Helper", uploadedFiles);
if (uploadedFiles) {
uploadedFiles.forEach((file) => {
file.fd =
process.env.AWS_BUCKET_URL +
((folderName ? folderName + "%5C" : "") +
timestamp +
file.filename.replaceAll("\\", "%5C"));
});
sails.log("filesUploaded", uploadedFiles[0]);
req.files = uploadedFiles;
setParams && setParams(uploadedFiles);
}
return proceed();
},
My aim to upload large files (images, videos, documents) from react application to s3 bucket . How can I do this?

How to recieve file object from google drive in vuejs?

I want to pick files from google drive as a file object. I am working in vuejs and hence used the vue-google-picker. Google picker is actually returning URL, that I am converting to a file. My code to convert to file:
async convertToFile(docs) {
return new Promise(
resolve => {
docs.map(doc => {
if (doc.url) {
gapi.load('client', function () {
gapi.client.load('drive', 'v3', function () {
var file = gapi.client.drive.files.get({ 'fileId': doc.id, 'alt': 'media' });
console.log(file)
file.execute(function (resp) {
console.log(resp)
resolve(resp)
});
});
});
}
});
}
)
}
console.log(file) shows object like this:
While console.log(resp) shows false. If I see the network tab, then I am receiving the base64 object of the file in preview tab.
How to receive that base64 object in code? What is a method of it? I am also open to any alternative method to receive object file from google drive.
You need to await for drive.files.get method
const file = await gapi.client.drive.files.get({ 'fileId': doc.id, 'alt': 'media' });
console.log(file.body) // here will be the data

NextJS API route error "TypeError: res.status is not a function"

I created a simple api endpoint named getFeed which is supposed to get feed content from Sanity CMS. But unexpectedly the endpoint is throwing an error "res.status is not a function". I know there is a similar question asked here , but in my case the api endpoint file is stored in the supposed pages/api directory. Here is the code snippet below.
import { NextApiResponse } from 'next'
import { client } from '../../lib/sanity/sanity'
export default async function getFeed(res: NextApiResponse) {
try {
const feeds = await client.fetch(
`*[_type == "post"]
{
_createdAt,
title,
description,
picture,
postDocId,
postedByUserId,
postedByUserName,
postedByUserImage
}`
)
return res.status(200).json({ feeds })
} catch (error) {
return res.status(500).json({ message: "Couldn't get post feed:\n", error })
}
}
Here is my folder structure
What am I doing wrong??
Try to specify also the req parameter and add a type to the response:
import { NextApiRequest, NextApiResponse } from 'next'
interface Data {
message?: string;
feeds?: <type-of-feeds>[];
}
export default async function getFeed(req: NextApiRequest, res: NextApiResponse<Data>) { ... }

React Native Woocommerce API fails when parameters are set

I recently decided to give React Native a shot. I am running into some trouble communicative with Woocommerce using the react-native-woocommerce-api.
When I get all the products, it works great, but when I try to set an attribute to the HTTP call, it fails.
This works:
componentDidMount() {
console.log("Loading products...");
Woocommerce.get("products", {}).then(response => {
console.log(response);
});
}
This doesn't (per_page added):
componentDidMount() {
console.log("Loading products...");
Woocommerce.get("products", {per_page: 3}).then(response => {
console.log(response);
});
}
Error thrown:
Object {
"code": "woocommerce_rest_authentication_error",
"data": Object {
"status": 401,
},
"message": "Invalid signature - the signature doesn't match.",
}
HTTP request that works:
http://www.example.com/wp-json/wc/v3/products?oauth_consumer_key=###&oauth_nonce=###&oauth_signature_method=HMAC-SHA256&oauth_timestamp=1560818379&oauth_version=1.0&oauth_signature=###=&
HTTP request that doesn't work:
http://www.example.com/wp-json/wc/v3/products?oauth_consumer_key=###&oauth_nonce=###&oauth_signature_method=HMAC-SHA256&oauth_timestamp=1560817909&oauth_version=1.0&oauth_signature=###=&per_page=3
I should also add that when adding per_page=3 using Postman, it works. I don't know what difference it makes, the HTTP calls are very similar, it seems that only the uri parameters order are different.
Any help is appreciated! Been stuck on this the whole freaking day. :/
Open react-native-woocommerce-api.js in node_modules\react-native-woocommerce-api\lib\
then goto line 195 (_getOAuth().authorize function) and change:
params.qs = this._getOAuth().authorize({
url: url,
method: method
});
to
params.qs = this._getOAuth().authorize({
url: url + '?' + this.join(data, '&'),
method: method
});

How to download file from server using nodejs

I want to download file from other website to my pc using expressjs
I tried to use: res.download to download but it seems to be worked on my own server only
Here is my code:
res.download('http://apkleecher.com/download/dl.php?dl=com.instagram.android', 'folder', function(err){
if (err) {
console.log(err);
} else {
}
});
And it return the error:
{ Error: ENOENT: no such file or directory, stat '/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android'
errno: -2,
code: 'ENOENT',
syscall: 'stat',
path: '/home/keitaro/Desktop/google-play/http:/apkleecher.com/download/dl.php?dl=com.instagram.android',
expose: false,
statusCode: 404,
status: 404 }
In my guess, the problem is in the path of url.
Turning my comment into an answer since it worked for you...
You can fetch a resource from a remote web server using either http.get() or the request() module in node. If you like to use promises for your asynchronous operations, then the request-promise module is a promisified version of the request module and works great.
You can also use just plain http.get(), but it's a lot more work because you have to read the stream, rather the results yourself and install appropriate error handling, all of which the request() module does for you in one simple call.
Here's a simple example using the request-promise module:
const rp = require('request-promise');
rp('http://www.google.com').then(function (htmlString) {
// Process html...
}).catch(function (err) {
// process error here
});
res.download requires a path to your local filesystem.
try this:
res.redirect("http://apkleecher.com/download/dl.php?dl=com.instagram.android")
best way to download remote file is use stream .its use small mount of memory
**npm i got**
//========================
const got=require('got');
const fs=require('fs');
const path=require('path');
file_downloader(link,file_name){
var file_path = path.join(__dirname,file_name);
await got.stream(encodeURI(link))
.on('response', async (data) => {
//first response check headers like ['content-length']
})
.on('error', async (error) => {
console.log("===========Stream Error======= ");
console.log(error);
console.log("===========//End Stream Error======= ");
})
.on('downloadProgress', async (progress) => {
console.log(file.name, progress);
})
.pipe(fs.createWriteStream(file_path));
}