I am currently working on an application which takes in image URLs in this format:
https://replicate.delivery/pbxt/Y45OPyjFe92FLqemk1Mmsr69gzruylefj5SxKqJInMmxCyABB/out-0.png
And need to send it to an API to check if it is explicit content. The issue is that the API only accepts .png or .jpg files and not an image URL. How can I convert this image URL into a sendable file?
This is what their docs say:
const axios = require('axios').default;
const fs = require("fs");
const FormData = require("form-data");
const form = new FormData();
form.append("providers", 'amazon, google');
form.append("file", fs.createReadStream("🖼️ path/to/your/image.png"));
const options = {
method: 'POST',
url: 'https://api.edenai.run/v2/image/explicit_content',
headers: {
authorization: 'Bearer 🔑 Your_API_Key',
'Content-Type': 'multipart/form-data; boundary=' + form.getBoundary()
},
data: form
};
axios
.request(options)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
However, I do not have the path to the file and instead solely the image URL. Any help would be greatly appreciated!
You need to make an extra request to get the image first, keep it in memory (alternatively, you could save the file and then read it with fs), and then make another request, which sends the image to the checking endpoint.
With axios, you can get the image as a stream, and then just pass it along with form-data.
Try this:
// get image as a stream
const getImgOptions = {
method: 'GET',
url: 'https://replicate.delivery/pbxt/Y45OPyjFe92FLqemk1Mmsr69gzruylefj5SxKqJInMmxCyABB/out-0.png',
responseType: 'stream'
};
let img;
try {
img = await axios.request(getImgOptions);
// got the image, now send it for checking
let uploadImg;
try {
const form = new FormData();
form.append("providers", 'amazon, google');
form.append("file", img.data);
const postImgOptions = {
method: 'POST',
url: 'https://api.edenai.run/v2/image/explicit_content',
headers: {
authorization: 'Bearer 🔑 Your_API_Key',
'Content-Type': 'multipart/form-data; boundary=' + form.getBoundary()
},
data: form
};
uploadImg = await axios.request(postImgOptions);
// do something with the result
console.log('check response: ', uploadImg.data);
} catch (error) {
console.error(error);
}
} catch (error) {
console.error(error);
}
Related
I have been trying for hours, tried CSV data, JSON data, tried it all I keep getting either a 415 error or a 400 error; if I can have any help that would be great, the documentation and the AI itself has not been at all helpful in trying to inject data to train a model
Text:
This is a text file for the OpenAI API.
It contains sample data for testing purposes.
Here is another line.
And another.
Code:
const FormData = require('form-data');
const fs = require('fs');
const API_KEY = 'MY_API_KEY';
const formData = new FormData();
formData.append('file', fs.createReadStream('./myfile.txt'), {
filename: 'myfile.txt'
});
axios.post('https://api.openai.com/v1/files', formData, {
headers: {
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
"Authorization": "Bearer " + API_KEY
}
})
.then(response => {
// Handle response
})
.catch(err => {
// Handle error
console.log(err)
});
From the documentation, you are missing the required purpose field...
Request body
file Required
...
purpose Required
The intended purpose of the uploaded documents.
Use "fine-tune" for Fine-tuning. This allows us to validate the format of the uploaded file.
const FormData = require("form-data");
const fs = require("fs");
const API_KEY = "MY_API_KEY";
const formData = new FormData();
formData.append("purpose", "search"); // 👈 adjust accordingly
formData.append("file", fs.createReadStream("./myfile.txt"), "myfile.txt");
axios
.post("https://api.openai.com/v1/files", formData, {
headers: {
...formData.getHeaders(), // this is simpler
authorization: `Bearer ${API_KEY}`,
},
})
.then((response) => {
// Handle response
})
.catch((err) => {
// Handle error
console.log(err.response?.data, err.toJSON());
});
Im trying to find a way to upload an image to Wordpress custom fields using axios. so far I've been able to upload to media but i want to upload directly to a field in a post type. this is what i have so far
const axios = require('axios');
const fs = require('fs');
var config = {
method: 'post',
url: 'url/wp-json/wp/v2/media',
headers: {
'Authorization': 'Basic dsgsgshhdh',
'Content-Type': 'application/json',
"Content-Disposition": 'form-data; filename="example.jpeg"',
"Content-Type": "image/jpeg",
},
data: fs.readFileSync('path to image', (err, data) => {
if (err) {
console.log(err);
}
}),
};
axios(config)
.then(function(response) {
console.log(JSON.stringify(response.data));
})
.catch(function(error) {
console.log(error);
});
the code above uploads to media but i want to upload to post type team member and field named image_url
normally with string data I post like this and pass it to my request and it works. b ut how do i post for images
var data = JSON.stringify({
"acf": {
"linkedin": "apo000 boys"
"image_url": ?????
}
});
I trigger / upload in node.js by calling the submit function inside a class. But in Node.js, req.body is empty. In fact, I append data to FormData in the submit function and send it to node.js. Where am I doing the problem?
Class
submit(){
const data = new FormData()
data.append('file', this.state.selectedFile)
data.append('ID', uniqid())
let url = "http://localhost:5000/upload";
axios({
method: "POST",
url: url,
data: data,
headers: {
"Content-Type": "application/json"
}
}).then(res => {
});
}
Node.js
app.post('/upload', (req, res) => {
axios.post('https://....php', req.body, {
}).then(function (response) {
}).catch(function (error) {
console.log('errorserver', error);
});
});
Try to put file after text like this.
submit(){
const data = new FormData()
data.append('ID', uniqid())
data.append('file', this.state.selectedFile)
let url = "http://localhost:5000/upload";
axios({
method: "POST",
url: url,
data: data,
headers: {
"Content-Type": "application/json"
}
}).then(res => {
});
}
In my node application, I want to get a file from one server, and then upload it into another server. I have the following code:
const axios = require("axios");
const FormData = require("form-data");
const { createWriteStream, createReadStream } = require("fs");
const response = await axios({
url: "https://first-server/image.png",
method: "GET",
responseType: "stream",
});
await new Promise((res) => {
response.data.pipe(
createWriteStream("someFile.png").on("finish", () => {
res();
})
);
});
const form = new FormData();
form.append("file", createReadStream("./someFile.png"));
const postHeaders = {
headers: {
Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("https://second-server.com/api", form, postHeaders)
.then((response) => {
console.log(JSON.stringify(response.data));
})
This code works, but I think it's not the right way to do this, since it writes the retrieved file into the local disc before posting it again into the second server. I need to be able to upload the file without writing it into the local disc. Is there any way?
Just replace form.append("file", createReadStream("./someFile.png")); with
form.append("file", response.data);
Both response.data and createReadStream("./someFile.png") are readable stream.
Note: You can directly transfer returned stream data without any need to create temporary file.
const axios = require("axios");
const FormData = require("form-data");
axios({
url: "http://localhost:3000/temp.png",
method: "GET",
responseType: "stream",
}).then(response => {
response.data.on("data", function(data) {
const form = new FormData();
form.append("file", data);
const postHeaders = {
headers: {
// Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("http://localhost:8000/api", form, postHeaders)
.then((response) => {
// console.log(JSON.stringify(response.data));
})
.catch(function(error){
console.log(error)
});
});
})
.catch(function(error){
console.log(error)
});
Hello I am implementing an API endpoint where I can send a file coming from aws S3. What I have done is I get the file in from my s3 bucket
let file_data = await S3.getObject(params).promise();
let buf = Buffer.from(file_data.Body);
const file = buf.toString("base64");
Now I want to send the file to other API for verification purposes. I tried something like this but doesn't seems to work
var data = new FormData();
const data_file = fs.createReadStream(fs.createWriteStream(file));
data.append("document", data_file);
var config = {
method: "post",
url: `${process.env.URL}/verify_file`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Bearer ${token}`,
...data.getHeaders(),
},
data: data,
};
try {
const res = await axios(config);
console.log(res.data);
} catch (error) {
console.error("sendPassport", error);
}
I found my solution. I create a file from a buffer that I get from AWS S3. Then save it in my current working directory.
let file_data = await S3.getObject(params).promise();
const buffer = Buffer.from(file_data.Body, "utf8");
// Create and download a file
fs.writeFileSync(
`${process.cwd()}/public/tmp/${data.filename}`,
buffer
);
Then I converted the file into stream using fs.createReadStream() function then send send the file
var data = new FormData();
const data_file = fs.createReadStream(`${process.cwd()}/public/tmp/${data.filename}`);
data.append("document", data_file);
var config = {
method: "post",
url: `${process.env.URL}/verify_file`,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Bearer ${token}`,
...data.getHeaders(),
},
data: data,
};
try {
const res = await axios(config);
console.log(res.data);
} catch (error) {
console.error("sendPassport", error);
}
// Delete the file
fs.unlinkSync(file_path);