I use rn-fetch-blob to upload an image. This works correctly in Android but does not work in iOS.
I use data parameter in response to create image link , and when I check response from iOS I found data is null in iOS response . I don't know why why data parameter is null when status is 200.
I tried all answers for same issues but they did not work for me!
code for Upload Image:
export const UploadImageService2 = async (
file: any,
): AxiosRequestConfig => {
console.log("UploadImageService2");
console.log("file: " + file);
let seps = `${file.path}`.split('/');
let filename = seps[seps.length - 1];
var fp = file.path + "";
const realPath = Platform.OS === 'ios' ? fp.replace('file://', '') : fp;
console.log("fb: " + fp);
console.log("filePath: " + realPath);
const data = [
{
name: 'Files',
filename,
type: file.mime,
// binary field data from a file path, use `wrap` method to wrap the path
data: RNFetchBlob.wrap(decodeURIComponent(realPath)),
// binary field data encoded in BASE64
// data: RNFetchBlob.base64.encode(file),
},
];
console.log("dataObj: " + JSON.stringify(data));
const response = await RNFetchBlob.fetch(
'POST',
`${BaseUrl}api/image`,
{
Authorization: 'Bearer ',
'Content-Type': 'multipart/form-data',
},
data,
);
return {
...(response ? response : {}),
...file,
};
};
That's function called by this:
_uploadSingleImage = async (file: any, sendCheckupForm) => {
console.log("_uploadSingleImage");
console.log("_file: " + JSON.stringify(file));
let response = await UploadImageService2(file);
// let response = await UploadImageService(file);
console.log('resp=>>>', response)
if (get(response, ['respInfo', 'status']) === 200) {
console.log("okkk");
const responseData = get(response, ['data'], file.name);
console.log("responseData: " + JSON.stringify(responseData));
const fileUrl = responseData.replace(/^"(.+(?="$))"$/, '$1');
// const fileUrl = 'myTestImage';
const attachedFiles = this.state.attachedFiles.map(i => i.path === response.path ? { ...i, status: 'success', FileName: fileUrl } : i);
console.log("attachedFiles: " + JSON.stringify(attachedFiles));
this.setState({ attachedFiles });
console.log('fileUrl', fileUrl)
this.setState({ receptionImage: fileUrl });
if (sendCheckupForm) {
// this.setState({showCheckupForm: false});
this.props.sendCheckupForms(
this.props.token,
this.props.orderDetails.Id,
{
fileList: [fileUrl],
},
);
this.props.getOrder(this.props.token, this.props.orderId);
}
} else {
console.log("Erorrr");
const attachedFiles = this.state.attachedFiles.map(i => i.path === response.path ? { ...i, status: 'error' } : i);
this.setState({ attachedFiles });
}
};
This is example Json response for rn-fetch-blob in iOS:
{ taskId: 'jgd8phv6w98zryggebvvkg',
type: 'utf8',
respInfo:
{ redirects: [ 'https://cp.azmayeshonline.com/api/image' ],
status: 200,
timeout: false,
taskId: 'jgd8phv6w98zryggebvvkg',
headers:
{ 'x-aspnet-version': '4.0.30319',
'Content-Length': '42',
'x-frame-options': 'AllowAll',
Date: 'Tue, 27 Oct 2020 19:34:43 GMT',
Expires: '-1',
Server: 'Microsoft-IIS/10.0',
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-cache',
'x-powered-by': 'ASP.NET',
Pragma: 'no-cache' },
respType: 'json',
state: '2',
rnfbEncode: 'utf8' },
info: [Function],
array: [Function],
blob: [Function],
text: [Function],
json: [Function],
base64: [Function],
flush: [Function],
session: [Function],
readStream: [Function],
readFile: [Function],
exif: null,
filename: 'IMG_0002.JPG',
path: '/Users/mesimac/Library/Developer/CoreSimulator/Devices/52589261-2055-4237-9DED-E4F8D71FD25B/data/Containers/Data/Application/5FC9EEDF-5710-4935-9380-F03114B291CF/tmp/react-native-image-crop-picker/7EF8432F-53A3-4A41-8068-159A5990623C.jpg',
height: 1024,
width: 1541,
data: null,
modificationDate: '1441224147',
localIdentifier: 'B84E8479-475C-4727-A4A4-B77AA9980897/L0/001',
size: 304799,
sourceURL: null,
mime: 'image/jpeg',
cropRect: null,
creationDate: '1255122560',
status: 'loading' }
Anyone suggestions for how I can handle this?
Try using:
data:RNFetchBlob.wrap(realPath)
instead of:
data:RNFetchBlob.wrap(decodeURIComponent(realPath))
The rest of your code looks fine. Anyway, you are replacing the fp.replace('file://', ''), which is needed for iOS.
This is how I did it in my code:
data:RNFetchBlob.wrap(this.state.file.uri.replace("file://", ""))
Related
I want download file on my ionic mobile app from amazon S3 but I have this issue Origin capacitor://localhost is not allowed by Access-Control-Allow-Origin.
So I add "capacitor://localhost" on my CORS configuration on amazon S3 like this :
[
{
"AllowedHeaders": [
"*"
],
"AllowedMethods": [
"HEAD",
"GET",
"PUT",
"POST",
"DELETE"
],
"AllowedOrigins": [
"*",
"capacitor://localhost"
],
"ExposeHeaders": []
}
]
but I have always the same issue.
My download function :
async downloadResource(filename: string) {
try {
this.url = this.changeSpecialCharacter(this.urlFolder + filename);
let extention = this.getFileExtension(filename);
filename = this.getFileName(filename);
if (!filename.includes(extention)) {
filename = filename + '.' + extention;
}
if (!filename) filename = this.url.split('\\').pop().split('/').pop();
const response = await fetch(this.url, {
headers: new Headers({
'Origin': 'capacitor://localhost'
}),
mode: 'cors'
});
console.log(' response '+JSON.stringify(response));
const blob = await response.blob();
const blobUrl = URL.createObjectURL(blob);
console.log(' blobUrl '+JSON.stringify(response));
const result = await Filesystem.writeFile({
path: filename,
data: blobUrl,
directory: Directory.Documents,
encoding: Encoding.UTF8
});
console.log('File written', result);
} catch (e) {
console.error('error fetch '+e);
}
}
I test also with const response = await fetch("https://file-examples.com/storage/feeb72b10363daaeba4c0c9/2017/10/file_example_JPG_100kB.jpg", {mode: 'cors'}); I have the same issue. So the problem is from the device
odule.export.createCertificate = async (event, context, cb) => {
let data = JSON.parse(event.body);
try{
const params = {
TableName: CERTIFICATE_TABLE_NAME,
Item:{
certificationId: data.id,
certificationName: data.certificationName,
certificationProvider: data.certificationProvider,
certificationLevel: data.certificationLevel,
certificationValidationId: data.certificationValidationId,
dateOfCertification: data.dateOfCertification,
dateOfExpiry: data.dateOfExpiry
},
ConditionExpression: "attribute_not_exists(certificationId)"
}
await documentClient.put(params).promise();
cb(null,{
statusCode: 201,
body: JSON.stringify(data)
});
}catch(err){
cb(null,{
statusCode: 500,
body: JSON.stringify(err.message)
});
}
};
module.export.createCertificate
I having an handler above and I figured I haven't defined the createCertifiacte but How I would define I couldn't know
I am trying to integrate a POST API call from a lambda function using Node.js 12.x.
I tried like below:
var posturl = "My post api path";
var jsonData = "{'password':'abcdef','domain':'www.mydomain.com','username':'abc.def'}";
var req = require('request');
const params = {
url: posturl,
headers: { 'jsonData': jsonData }
};
req.post(params, function(err, res, body) {
if(err){
console.log('------error------', err);
} else{
console.log('------success--------', body);
}
});
But when I am execute it using state machine, I am getting the below exception:
{
"errorType": "Error",
"errorMessage": "Cannot find module 'request'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
"trace": [
"Error: Cannot find module 'request'",
"Require stack:",
"- /var/task/index.js",
"- /var/runtime/UserFunction.js",
"- /var/runtime/index.js",
" at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)",
" at Function.Module._load (internal/modules/cjs/loader.js:667:27)",
" at Module.require (internal/modules/cjs/loader.js:887:19)",
" at require (internal/modules/cjs/helpers.js:74:18)",
" at Runtime.exports.handler (/var/task/index.js:8:14)",
" at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
]
}
Here the posturl is my api path and jsondata is my key value pair data.
So How can I call a POST API from lambda function? How can I pass the entire jsondata key when call API? How can I parse the response after the service call?
Update: I have tried like below
All my details are passing with a key jsonData, where I can specify that? Without that key, it will not work.
exports.handler = (event, context, callback) => {
const http = require('http');
const data = JSON.stringify({
password: 'mypassword',
domain: 'www.mydomain.com',
username: 'myusername'
});
const options = {
hostname: 'http://abc.mydomain.com',
path: 'remaining path with ticket',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = http.request(options, (res) => {
let data = '';
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(data);
req.end();
};
source : How to Make an HTTP Post Request using Node.js
const https = require('https');
const data = JSON.stringify({
name: 'John Doe',
job: 'Content Writer'
});
const options = {
hostname: 'reqres.in',
path: '/api/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = https.request(options, (res) => {
let data = '';
console.log('Status Code:', res.statusCode);
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Body: ', JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: ", err.message);
});
req.write(data);
req.end();
I'm using react-native-camera(^0.6.0) in my app, I have to upload the recorded video to server as multipart data. In android they are posting like this,
{
_parts: [
[
'file',
{
name: 'VID_20181130_150959.mp4',
uri: 'file:///storage/emulated/0/DCIM/VID_20181130_150959.mp4',
type: 'video/mp4'
}
]
]
}
but in iOS the file path is returning as assets-library://asset/asset.mov?id=41B76A24-1018-46C1-A658-C1EFFC552FD0&ext=mov but if I post the assets path it's not uploading.
{
_parts: [
[
'file',
{
name: '41B76A24-1018-46C1-A658-C1EFFC552FD0.mov',
uri: 'assets-library://asset/asset.mov?id=41B76A24-1018-46C1-A658-C1EFFC552FD0.mov',
type: 'video/mov'
}
]
]
}
Can anyone help me out with this????
I'm using iPhone 6 for debugging the code,
var url = DomainAPI.lashHostname + '/attachments?token=' + value + '&class=Quick';
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: JSON.stringify(formData)
}).then((response) => response.json())
.then((responseData) => {
console.log('responseData------->************$$$$$$$$$$$' + JSON.stringify(responseData));
if (responseData.error.code == 0) {
this.sendFiletoServer(responseData.id, value);
} else {
this.setState({ loading: false });
Actions.pop();
}
}).catch((err) => {
console.log('responseData-------> err ************$$$$$$$$$$$' + JSON.stringify(err));
this.setState({ loading: false });
Actions.pop();
});
See This code worked for me hope it helps
let formData = new FormData();
formData.append("videoFile", {
name: name.mp4,
uri: video.uri,
type: 'video/mp4'
});
formData.append("id", "1234567");
try {
let response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
});
return await response.json();
}
catch (error) {
console.log('error : ' + error);
return error;
I'm building an app with Ionic 2. I need to take a photo from gallery or camera and upload this picture to my server. I have this code that opens the Gallery and takes a picture. without base64Image, how can upload image.
private accessGallery(): void {
let options = {
quality: 75,
// sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
// destinationType: this.camera.DestinationType.DATA_URL,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
// encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.imagePicker.getPictures(options).then((results) => {
this.imageURI = new Array();
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
this.imageURI.push(normalizeURL(results[i]));
}
console.log("Body images Name*******:-=" + this.imageURI);
this.uploadFile();
}, (err) => { });
}
uploadFile() {
let body:any = new FormData();
body = {
images: this.imageURI
}
let headers = new Headers({
'token': this.token,
'sid': this.sid,
'user': this.user,
'to': this.to,
'node': this.node,
'type': 'image'
});
let options = new RequestOptions({ headers: headers });
console.log("header ----" + JSON.stringify(headers));
console.log("images data body----" + JSON.stringify(body));
this.http.post(this.apiURL, body, options)
.map(res => res.json())
.subscribe(
data => {
console.log(data);
},
err => {
console.log("ERROR!: ", err);
}
);
}
Error :- ERROR!: Response with status: 0 for URL: null