i'm using api platform to create end Point to handle images upload.
My api require a file type to make a post request.
This is an example of post request using post man :
I want to handle sending images with axios using react native.
I created a post request like this :
this.setState({
avatarSource: source,
});
console.log(this.state.avatarSource.uri);
const data = new FormData();
data.append('file', {
uri: this.state.avatarSource.uri,
// show full image path in my device
// file:///storage/emulated/0/Pictures/image-c40b64fc-6d74-46a7-9016-191aff3740dd.jpg
});
axios
.post(`${API.URL}/media_objects`, data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then((resp) => console.log(resp))
.catch((err) => console.log(err.message));
}
});
I'm sending the full path of image in my phone to the api but i got "Network Error"
I fixed the problem by commenting this line in ReactNativeFlipper.java :
NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
NetworkingModule.setCustomClientBuilder(
new NetworkingModule.CustomClientBuilder() {
#Override
public void apply(OkHttpClient.Builder builder) {
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); // add comment here and build android
}
});
client.addPlugin(networkFlipperPlugin);
client.start();
Related
I want to upload an image from react native app to backend in symfony via axios.
here is the code of the front end :
const [pickedImage, setPickedImage] = useState("");
const submitPhoto = async () => {
try {
const result = await ImagePicker.launchImageLibraryAsync();
setPickedImage(result);
let formData = new FormData();
formData.append("uploaded_image", {
uri:
Platform.OS === "android"
? pickedImage.uri
: pickedImage.uri.replace("file://", ""),
name: "tata.jpeg",
type: "image/jpeg",
});
const response = await axios({
method: "post",
url: "http://192.168.1.3:8000/upload",
data: formData,
});
} catch (error) {
console.log(error)
}
};
here is the code of the backend in Symfony :
public function postImage(Request $request)
{
//... some code
$content = $request->files->get("uploaded_image");
// ... handle the image in content
}
As I can see, $content is NULL. And to confirm it, I attached a screenshot of the profiler of symfony.
I tried to add "Content-type": "multipart/form-data" in the axios call, but i get : "Missing boundary in multipart/form-data POST data"
Does anyone know how I can properly upload the image from react native to Symfony ?
Thanks in advance.
EDIT 1 :
When using POSTMAN, the backend works as you can see in the two following images :
POSTMAN REQUEST :
PROFILER SYMFONY :
As I said, when i use Axios with the right header (multipart/form-data), I get a message error :
Missing boundary in multipart/form-data POST data
.
I tried to use fetch, and it works now ! I dont know why :
let response = await fetch(
"http://192.168.1.3:8000/upload",
{
method: "post",
body: formData,
headers : {
'Content-Type' : 'multipart/form-data;'
}
}
)
It is weird, but I dont know why it works now.
I think that you get a base64 in your back-end side, then you have to convert it with something like :
$data = base64_decode($content);
file_put_contents($filePath, $data);
I have tried different ways with fetch or axios to POST to my server but it seems that the post body turns empty . My initial code is this.
So the connection to the server is good. I have configured server to respond with $_POST variables received but the $_POST return empty. This happens when I use JSON.stringify on body. I have also tried with FormData and it works fine but only on iOS. On my Android device and emulator I get Possible Unhandled Promise: Network request failed error (both https and http).
And I want to make it work on both iOS and Android. So till now I have manage to send post with formData only on iOS.
Any Solutions that works on Android and iOS?
import FormData from "FormData";
export const login = (emailUsername, password) => {
var formData = new FormData();
formData.append("emailUsername", emailUsername);
formData.append("password", password);
return async dispatch => {
const response = await fetch(
"https://myserver.net/api/app/auth.php",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
emailUsername:emailUsername,
password:password
})
}
);
if (!response.ok) {
throw new Error("Something went wrong!");
}
const resData = await response.json();
console.log(resData);
};
};
Thanks to #bug I have find a solution. I was expecting to receive POST content to my $_POST or $_REQUEST variables on my server, but instead I had to get them this way.
$post_data = json_decode(file_get_contents('php://input'));
I am trying to download an image from url then share it via whats app and other social media as an image format, I tried some method but I couldn't, my code is as follow:
let filePath = null;
const configOptions = {
fileCache: true,
};
RNFetchBlob.config(configOptions)
.fetch('GET', url)
.then(async resp => {
filePath = resp.path();
let options = {
url: filePath
};
await Share.open(options);
await RNFS.unlink(filePath);
});
I tried also
RNFetchBlob.fetch("GET",url,{
Authorization : 'Bearer access-token...',
})
.then(resp => {
console.log(resp)
let shareImageBase64 = {
title: "React Native",
message: "Hola mundo",
url: `data:image/png;base64,` + resp.base64(),
};
Share.open(shareImageBase64);
})
it does open the share option but there is no image, only the message can be shared.
This is an open issue in github, the issue is only on IOS when sharing with whats app. The problem is that the message under shareImageBase64 overrides the url and you are sharing the message only, a workaround is to remove the message and you will be able to share your image successfully.
i am using the following code to but i keep getting in android, which was showing "Network request failed", but it was no problem if i not append photo file data in the FormData. Why I am getting this problem?
const data = new FormData();
data.append("name", "testName"); // you can append anyone.
data.append("photo", {
uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==',
type: 'image/png', // or photo.type
name: 'testPhotoName.png'
});
fetch('https://ptsv2.com/t/1gfl7-1544694996/post', {
method: "post",
body: data
}).then(res => {
console.log(res);
});
I'm trying to upload a picture to strapi from react native.
async function uploadPicture(uri) {
var data = new FormData();
data.append('files', {
uri: uri.replace('file://', ''),
name: uri,
type: 'image/jpg'
});
// Create the config object for the POST
// You typically have an OAuth2 token that you use for authentication
const config = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data;'
},
body: data
};
const fetchPromise = fetch('http://<host>:1337/upload', config)
console.log(fetchPromise)
return await fetchPromise
}
I get a 200 status code but no new picture is listed on the uploads page.
Oh! I figured it out using simple-http-upload-server to test the uploads. The problem was that I was setting the name of the file to be the uri. This would probably cause an error on strapi when creating the file on the server folder. It should return an error code nonetheless.