Success upload file via postman but fail on front-end (vue) - vue.js

I have been success upload file via postman and file has been moved to the folder, but when I try on front-end (vuejs) nothing error but file is not moved,
_upload(){
let fd = new FormData();
fd.append('photo', this.photo); // this.photo is base64 data
this.axios.post('upload_photo', fd, {
headers: {
'content-type': 'multipart/form-data'
}
}
).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}

try this:
First create the variable.
var photo = ref();
bind to input file tag
<input
id="photo"
type="file"
name="photo"
hidden
#change="previewImage"
#input="photo= $event.target.files[0]"
/>
This is the upload function
const uploadImg = () => {
var formData = new FormData();
formData.append("photo", photo);
(async () => {
await axios
.post(route("editImg"), formData, {
headers: {
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "multipart/form-data",
},
credentials: "same-origin",
})
.then((response) => {
console.log(response);
.catch((e) => {
console.log("err = ", e);
});
})();
};

Related

How do I use Async Storage to save Data Locally after calling fetch in react native?

I want to use Async storage. Each time I call without the async function like this
FunctionLogin = () =>{ //other methods here ........ }
and this does not have await anywhere, it saves to the database but when i use let email = AsyncStorage.getItem('email'); to call it back, it does not return anything like the email just [Object object] is what i see
how do I resolve this
the fetch method to save to async storage looks like this
`FunctionLogin = async () =>{
//navigation.replace('VirtualAccountPage');
let item = {email, password,phone};
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(responseJson =>{
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
}`
the function to call it back, so it can be used as persistence looks thus
` FunctionUserDetails = () => {
let email = AsyncStorage.getItem('email');
let phone = AsyncStorage.getItem('telephone');
//navigation.replace('Dashboard');
alert(email);
};`
How do i get this to work?
I want to be able to save data locally using async storage so i can be able to persist the data on some other screens etc. I tried several things to see if It could work as expected, i do not get to see it work as i want.
to get the value from AsyncStorage you need to use await and the function should start with async
fetch('https://xxxxxxxxxxxxxxxx/api/sign-up', {
method: 'POST',
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.message === 'User created Successfully') {
await AsyncStorage.setItem('email', email);
await AsyncStorage.setItem('phone', phone);
alert('I am Registered');
navigation.replace('VirtualAccountPage');
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});
const FunctionUserDetails = async () => { // change this
let email = await AsyncStorage.getItem('email'); // change this
let phone = await AsyncStorage.getItem('telephone'); // change this
//navigation.replace('Dashboard');
alert(email);
};`
Install this updated async-storage npm
Try implementing using below code:
fetch('https://xxxx/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify(item),
})
.then(response => response.json())
.then(async (responseJson) =>{ // add async here
if (responseJson.stausCode === 200) {
await AsyncStorage.setItem('name', name);
} else {
alert(responseJson);
}
})
.catch(error => {
console.error(error);
});

Axios React upload jpg

I have photo file taken with ImagePicker, and I need upload it to server, using axios, and I need send type as a string with this photo.
My code here
const axiosMultipart = axios.create({
timeout: 3000,
baseURL: BASE_URL,
headers: {
'Content-Type': 'multipart/form-data'
}
})
uploadDocs(token,type,photo){
let data = new FormData();
data.append('photo', photo);
data.append('type', type);
return axiosMultipart
.post(
`uploadDocs`,
{data},
{
headers: {
Authorization: token,
},
}
)
.then((response) => {
return response.data;
})
.catch((error) => console.log("uploadDocs: " + error));
};
Server response is error_code 400
What is wrong here?
Also I have code on php with a working request
Try With Below Code,
var photo = {
uri: file,
type: 'image/jpeg',
name: 'photo.jpg',
};
var FormData = require('form-data');
var form = new FormData();
form.append('photo', photo);
form.append('filetype', filetype);
axios({
method: 'post',
headers: {
"Accept": "application/json",
'Content-Type': 'multipart/form-data',
"Authorization": authData
},
data: form,
url: `${base_url}`,
}).then(async (result) => {
console.log("uploadFile detail Response===>", result);
}).catch((error) => {
console.log("uploadFile detail error===>", error);
callback({ status: false, result: error })
});

How to upload image to server in React Native

I'm trying to upload image by using React Native axios. But I get this response. I tried every solutions but it didn't work. I'm using react-native-image-picker to get image
{ result: null,
message: 'Wrong access',
error: true,
type: 'command_not_found' }
Here is my code
ImagePicker.showImagePicker(options, (response) => {
let formData = new FormData();
formData.append('image', { uri: response.uri, name: response.fileName, type:response.type });
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios({
url: "URL",
method: 'POST',
data: formData,
config
})
.then(result => console.log(result))
.catch(error => console.log(error))
}
Try with raw fetch api.
const createFormData = (photo) => {
const data = new FormData();
data.append("photo", {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === "android" ? photo.uri : photo.uri.replace("file://", "")
});
return data;
};
and then try to upload it again
fetch("http://localhost:3000/api/upload", {
method: "POST",
body: createFormData(photo)
});

How to get Html code by fetching web API response?

When we are trying to fetch html code via fetch API response but we are enable to get it because it return "Unexpected Token <"
onLoginService2 = async () => {
try {
var hittingURl = "https://members.iracing.com/membersite/Login?username=dave#rms55.com.au&password=rms55Pa55&utcoffset=-600&todaysdate=1558055491688&checkbox=0";
const myRequest = new Request(hittingURl.toString(),
{
method: 'POST',
headers: {
'Accept': 'text/html',
'Content-Type': 'text/html;charset=ISO-8859-1',
},
timeout: 1000,
// body: JSON.stringify("")
}
);
fetch(myRequest)
.then((response) => console.log("abcdefghijklmon--> "+JSON.stringify(response)))
.then((data) => {
console.log("RESPONSERR----> ",data+"");
// this.setState({ isLoading: false })
// this.onLoginSuccessFull(responseJson)
})
.catch((error) => {
this.setState({ isLoading: false })
console.log("response--31" + error);
})
} catch{
}
// }
}
The response of first then has a method .text(), which return Promise
Try this
fetch(myRequest)
.then(resp => resp.text())
.then(text => {
//text is html
})
*Just copy the above and run in console to see the result.

How to upload a file from asset-library to Express server in React Native?

I have my video file assets-library://asset/asset.mov?id=766BDDA3-F0EB-43B3-B719-4EA851692B91&ext=mov and I am trying to now upload it to my Express server.
const uri = 'http://localhost:3000/upload';
const formData = new FormData();
formData.append('file', 'assets-library://asset/asset.mov?id=766BDDA3-F0EB-43B3-B719-4EA851692B91&ext=mov');
fetch(uri, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data boundary=gc0p4Jq0M2Yt08jU534c0p'
},
body: formData
})
.then(res => {
console.log({ res });
})
.catch(err => {
console.log(err);
});
My Express Server API endpoint:
app.post('/upload', upload.single('file'), (req, res) => {
console.log(req.file);
res.send('Done');
});
The console.log(req.file) returns undefined.
Do I need to do an extra step in between?
As per Gavin's comment, I tried out RNFetchBlob.
RNFetchBlob.fetch(
'POST',
'http://localhost:3000/upload',
{
'Content-Type': 'multipart/form-data'
},
[
{
name: 'file',
filename: 'vid.mov',
data: RNFetchBlob.wrap(file)
}
]
)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
My application crashes without any logs on Xcode or in the Debugger.