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": ?????
}
});
Related
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);
}
I am struggling from taking pictures with expo camera on react native and sending the cache image to my node.js backend server and then my backend server appends this to a formdata object and sends it to my webservice. I searched a lot about the operations between my frontend and backend but couldn't find the exact true answer.
My express-node backend server getting images with multer.
I have a react native frontend code like below in order to send my image data I got as returned object of takePictureAsync method of expo-camera:
CLIENT SIDE
//react native client side
const takePicture = async () => {
if (cameraRef.current) {
const options = { quality: 0.5, base64: true, skipProcessing: true };
const data = await cameraRef.current.takePictureAsync(options);
const source = data.uri;
if (source) {
await cameraRef.current.pausePreview();
setIsPreview(true);
uploadFile(source);
console.log('picture source', source);
}
}
};
Then I get 404 status error from my backend when I try to send this image data like below with axios to my node.js backend server:
//react native client side
async function uploadFile(photo) {
const formData = new FormData();
formData.append('file', {
uri: photo,
name: 'test',
mimetype: 'image/jpeg',
});
await axios
.post('http://MyLocalIpAdress:3000/photo-upload', formData, {
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
console.log(res.data);
return res.data;
});
}
SERVER SIDE
My Node.js backend endpoint is as below:
router.post(
'/photo-upload',
multer({ storage: multer.memoryStorage() }).single('file'),
async (req, res) => {
if (req.file) {
try {
// Transfers uploaded image through webservice
const form = new FormData();
form.append('file', req.file.buffer, {
contentType: req.file.mimetype,
filename: req.file.originalname,
});
res.status(200).send({
message: 'Success'
});
} catch (err) {
res.status(500).send({
message: `Could not upload the file: ${req.file.originalname}. ${err}`,
});
}
} else {
return res.status(400).send({ message: 'Please upload a file!' });
}
})
I couldn't figure out whether I'm doing things wrong on server side or client side
and the way of doing it.
I faced same issue with sending image data to backend using formData. There are a couple of tricks to solve this:
Solution 1:
const formdata = new FormData();
formdata.append('image[]', {
name: 'test',
type: imageurl?.type,
uri:
Platform.OS !== 'android'
? 'file://' + photo
: photo,
});
const res = await axios.post('http://MyLocalIpAdress:3000/photo-upload', formdata, {
headers: {
Accept: '*/*',
'Content-type': 'multipart/form-data',
},
});
Solution 2: (My personal choice) is to use a library to upload the data. rn-fetch-blob is something that I have used to solve this. If you plan to use this, go through the documentation and implement it.
RNFetchBlob.fetch('POST', 'http://MyLocalIpAdress:3000/photo-upload',
{
Authorization : "Bearer access-token",
'Content-Type' : 'multipart/form-data',
}, [
// element with property `filename` will be transformed into `file` in form data
{ name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
// custom content type
{ name : 'avatar-png', filename : 'avatar-png.png', type:'image/png', data: binaryDataInBase64},
// part file from storage
{ name : 'avatar-foo', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(path_to_a_file)},
// elements without property `filename` will be sent as plain text
{ name : 'name', data : 'user'},
{ name : 'info', data : JSON.stringify({
mail : 'example#example.com',
tel : '12345678'
})},
]).then((resp) => {
// ...
}).catch((err) => {
// ...
})
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 => {
});
}
I want to upload image to the database. However, when I use fetch method with 'Content-Type': 'multipart/form-data' but I cannot get the appended data in the server side. It shows that I have no data in the body.
Below is fetching part of the coding
editProfile = () => {
let bodyData = new FormData();
let photo={
uri:this.state.uri,
type:this.state.type,
fileName:this.state.fileName,
}
bodyData.append('transactionCode', 'UPDATEPROFILE');
// bodyData.append('photo', photo);
console.log(bodyData);
fetch(URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: bodyData,
}).then((response) => response.json())
.then((responseJson) => {
alert(responseJson);
})
.catch((error) => {
alert(error);
});
}
This is the example of how i check the data at the server side
const custfunction = function (req, res) {
console.log(req.body);
}
When i console.log(req), it shows body:{} is empty
Alright, I just find out the problem. I need to use Multer to handle multipart/form-data in the backend. Thanks a lot.
https://www.npmjs.com/package/multer
I am hitting a get api in react similar to http://www.orimi.com/pdf-test.pdf which needs some secret information which is available only at middleware written in node. I want to open the pdf on client side(browser). So I am hitting the proxy get api which will hit the middleware and middleware will hit the backend server, but I am getting unable to open document and blank pdf. Can anyone tell me what is wrong with this code?
fetch(pdfApiMiddlewareUrl, {
method: "GET",
headers: {
"Content-Type": "application/pdf",
'Content-Disposition': 'inline; filename=your_file_name'
},
responseType : 'blob'
})
.then(res => res.blob())
.then(response => {
var blobUrl = URL.createObjectURL(response);
window.open(blobUrl);
})
.catch(error => {
console.log("HEREEEEEEEE");
console.log(error);
});
MIDDLEWARE CODE:
var urlEndPointsToHit = decodeURIComponent(req.query.urlToHit);
var url = urlEndPointsToHit+'?secret='+secretInfo;
var options;
options = {
url: url,
method: 'GET',
headers: {
'Content-type': 'application/pdf'
},
};
if(options) {
options.qs = req.query || {};
}
request(options, function(err, resp, body) {
req.locals = body;
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Cache-Control', 'no-cache');
next();
});