I'm trying to build an app that give the user to upload and share photos. I'm using react native and expo-image-picker, after user upload photo its give back object with local uri (means that others users couldnt see the image too). I want to send post request to my express server and get back public url that every one could see.
import * as ImagePicker from "expo-image-picker";
import { Platform, Alert } from "react-native";
import axios from "axios";
export default async function getPhotoUri() {
if (Platform.OS !== "web") {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== "granted") {
Alert.alert("OOPS!", "Premmision denied", [{ text: "fuck" }]);
} else {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
console.log(result);
let dataform = new FormData();
dataform.append("file", { uri: result.uri, type: result.type });
const res = await axios.post(
`${myExpressServerBaseUrl}/photoUploads`,
{ data: dataform },
{
headers: {
"Content-Type": "multipart/form-data; ",
},
}
);
return result.uri;
}
}
}
}
the result object is:
Object {
"cancelled": false,
"height": 1152,
"type": "image",
"uri":"file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540yuvalsilver888%252FLetsGoOut/ImagePicker/0feddf94-cdb5-48d1-9d21-14eae84fbb6b.jpg",
"width": 1536,
}
the dataform is:
FormData {
"_parts": Array [
Array [
"file",
Object {
"type": "image",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540yuvalsilver888%252FLetsGoOut/ImagePicker/90a663b2-5308-46ce-8f30-6937473dd573.jpg",
},
],
],
}
i searched everywhere and couldnt find what to write in the server in the post request to get a public url back (i heard about imgur and tried but faild to make it work)
the backend code is:
const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(cors());
//post local image and give back public url
app.post("/photoUploads", async (req, res) => {
try {
const { data } = req.body;ז
res.json(data);
} catch (error) {
console.log(error.message);
res.json(false);
}
});