Upload Image with fetch / PUT doesn't upload image - react-native

I am trying to upload an image to the bunnycdn with fetch / PUT. I am trying to put the image into the body but it doesn't work this way. Is there anything i can change?
const uploadpicture = async () => {
console.log("uploadpic")
//here use then props.route.params.image etc
let randomid = uuid()
let bodyy = new FormData()
bodyy.append("image",props.route.params.image.uri)
const options = {
method: 'PUT',
headers: {
'content-type': 'application/octet-stream',
AccessKey: '185e0bd5-1e29-492e-811d6cde3520-4ebe-4c15'
},
body: bodyy
};
fetch(`https://storage.bunnycdn.com/premvanaprogr/${currentUserObject.uid}/${randomid}.jpg`, options)
.then(response => response.json())
.then(response => console.log(response))
.catch(err => console.error(err))
}

Related

how make put axios request with formData?

i tried to send data with text and file. i created formData to send it:
updateProduct(item){
let product = new FormData();
product.append('thumb', item.thumb)
product.append('weight', item.weight)
this.$store.dispatch('UPDATE_PRODUCT', product)
},
action in store:
UPDATE_PRODUCT({commit}, item){
const token = localStorage.getItem('token');
const config = {
headers: { Authorization: `Bearer ${token}`}
};
// console.log(token)
return axios.post(`${url}`, item, config)
.then((resp) => {
commit('UPDATE_PRODUCT_IN_STATE', resp)
return resp;
})
.catch((error) => {
console.log(error);
});
},
So i have 422 error. Why?

React native im trying to upload image everytime localuri.slpit not defined showing and {_parts:[[]]} and why this _parts coming while sending data

can anyone tell me what wrong with this code im trying to upload image using react-native-image-picker in react native.but it says localUri.split is not defined and sending data shows in inspect element as {_parts:[[]]} and why this _parts coming every post method ...please help me to figure out this..
const takeAndUploadPhotoAsync = async () => {
const token = await AsyncStorage.getItem("userToken");
let result = await launchImageLibrary();
if (result.cancelled) {
return;
}
let localUri = result.uri;
let filename = localUri.split('/').pop().split('#')[0].split('?')[0]
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
const url = `/auth/upload-prescription`;
let formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
setLoading(true);
const response = await api
.post(url, formData, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
})
.then((res) => {
showMessage({
message: "Your Prescription is Uploaded Successfully",
textStyle: {textAlign:'center'},
type: "success",
backgroundColor: "#202877",
});
})
.catch((error) => {
console.log(error.response);
});
dispatch({
type: "TAKE_AND_UPLOAD_PHOTO_ASYNC",
payload: response,
});
setLoading(false);
};

Getting 'Undefined' value outside Fetch API

I am new in react native, trying to assign fetch API response value to a local variable. But outside function shows an undefined value of the variable.
Here is code
const {
diesel_data
} = this.state
let currentHMR
let previous_HMR
let previous_EstEngHours
let isViolationPass_HMR
let asset_id = diesel_data[0].diselRequisitionDetails[0].asset_id
let current_hmr = diesel_data[0].diselRequisitionDetails[0].current_hmr
let requisitionId = diesel_data[0].requisitionId
this._indicator.startActivity()
fetch(url + 'Norms/DieselHmrViolation/' + asset_id + '/' + current_hmr + '/' + requisitionId, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((json) => {
this._indicator.stopActivity()
var list = json;
console.log(list)
if (!isBlank(list)) {
currentHMR = list.currentHMR
previous_HMR = list.previous_HMR
previous_EstEngHours = list.previous_EstEngHours
isViolationPass_HMR = list.isViolationPass_HMR
}
})
.catch((error) => {
console.error(error);
});
console.log('currentHMR', currentHMR)
I think you can do like this, wait until executing fetch (maybe you have to move this inside a async function)
let data;
await fetch('https://reqres.in/api/users/2', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.json())
.then(res => data = res)
.catch(err => console.log(err))
console.log('data', data);

Passing formData to upload image with nodeJS (Multer) -> 'react-native-image-crop-picker'

I have currently a problem when i want to uploads files from client mobiles devices to my backend (NodeJS) with MULTER.
I'm using 'react-native-image-crop-picker' to pick the images on the devices (from the library or the camera)
I have used formData to make the response as file to the backend but the req file is still undefined.
My front-end Code:
let response = await ImagePicker.openCamera({
height: 400,
width: 400,
cropping: true,
});<br>
let media = {
uri: response.path,
type: response.mime,
name: response.filename,
};<br>
let form = new FormData();
form.append('uploads', media);<br>
if (form !== null) {<br>
await Axios({
method: 'POST',
url: url,
data: form,<br>
headers: {
'Content-Type': 'multipart/form-data',
},
})
My backend :
router.post('/article', upload.single('uploads'), async (req,
res) =>
{<br>
try {
console.log(req.file);
} <br>catch (err) {
console.log(err.message);<br>
res.status(500).send('SERVOR ERROR');
}
});
front-end
back-end
console.log(req.file) = "UNDEFINED"
I have used to try with fs.readFile :
let d = {};
let e = await Fs.readFile(response.path, 'base64');
let form = new FormData();
form.append('uploads', e);
d.uploads = form;
let config = {'Content-Type': 'multipart/form-data'};
Axios.post(url, d, config)
.then((res) => console.log(res))
.catch((err) => console.error(err));
}
The req.file is still undefined but the req.body shows this :
req.file => undefined
req.body => { uploads: { _parts: [ [Array] ] } }

How should i use asyncstorage.setItem in this fetch method?

i want to add the async storage method to save my json response,
but i don't know how to add there specifically
i have already tried like this
UserRegisterationFunction = () => {
const { UserName } = this.state;
const { UserEmail } = this.state;
const { UserPassword } = this.state;
fetch('http://192.168.1.7/test/user_registration.php', {
method: 'POST',
headers: {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
body: JSON.stringify({
name: UserName,
email: UserEmail,
password: UserPassword
})
}).then((response) => response.json())
.then((responseJson) => {
AsyncStorage.setItem('token', responseJson)
// this._onValueChange(STORAGE_KEY, responseData.id_token),
Alert.alert(responseJson);
}).catch((error) => {
console.log(error)
});
i am getting my alert successfully but i don't know how should i add the responseJson or if i have used it correctly or not
You can use the asynchronous system or save successfully without using it.
To run asynchronously:
.then(async (responseJson) => {
await AsyncStorage.setItem('token', responseJson.id_token);
Alert.alert(responseJson);
}).catch((error) => {
console.log(error)
});
If your responseJson data is this:
Object {
id_token : "myid"
}
Use the getItem function on the following screen to check the value.
async componentDidmount() {
const tokens = await AsyncStorage.getItem('token');
alert(tokens); // You can see 'myid'
}
The JSON response is an object and you can't store the object directly in AsyncStorage. You can only store the object by converting it into a string.
To store the object:
AsyncStorage.setItem('KEY', JSON.stringify(object))
To retrieve the object:
const jsonObjectString = AsyncStorage.getItem('KEY')
const jsonObject = JSON.parse(jsonObjectString)