how can I upload an image from his path "file:///var/mobile/Containers/Data/Application/D6326867-A474-481F-B6B4-5A9A6251CC0E/tmp/cdv_photo_013.jpg" to firebase storage using Javascript ? Cause I know how to using Blob or File but not from a single path...
Here my resolved code :
uploadPicutre(uri:string, userUid: string){
let self = this;
return new Promise((resolve, reject) => {
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
callback(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
toDataUrl(uri, blob => {
self.refStoragePicture.child(userUid)
.put(blob).then(snapshot => {
self.refStoragePicture.child(userUid)
.getDownloadURL().then(function(url) {
resolve(url);
}).catch(function(error) {
reject(error);
});
}).catch( err => {
reject(err);
});
})
})
}
Related
This is a function that uploads an image to the firebase storage and then retrieves the URL using the 'getDownloadURL' function.
The uploading of images works fine but it fails to retrieve the URL as it is trying to access the URL while the image is still uploading.
Please solve this problem !!
const getGSTURI = async () => {
if (GSTLoading) {
return;
}
setGSTLoading(true);
const result = await DocumentPicker.getDocumentAsync({
copyToCacheDirectory: true,
});
console.warn(result);
setGSTName(result.name);
setGSTURI(result.uri);
setGSTLoading(false);
async function uploadGST(uri, name) {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.warn(e);
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", uri, true);
xhr.send(null);
});
const storageRef = ref(storage, `sellers/${sellerID}/${name}`);
uploadBytes(storageRef, blob).then(() => {
console.warn("GST Upload Successfull");
});
getDownloadURL(ref(storage, `sellers/${sellerID}/${name}`))
.then((url) => {
// `url` is the download URL for 'images ' stored in firestorage
console.log(url);
setGSTURL(url);
console.log(GSTURL);
})
.catch((error) => {
"Errors while downloading";
});
// We're done with the blob, close and release it
blob.close();
}
uploadGST(GSTURI, GSTName);
};
you have to wait for the uploadBytes function to complete before trying to retrieve the url
instead of
uploadBytes(storageRef, blob).then(() => {
console.warn("GST Upload Successfull");
});
you can use the await operator as below to wait for the task to complete
try {
await uploadBytes(storageRef, blob);
console.warn('GST Upload Successfull');
} catch (e) {
console.warn('GST Upload Failed', e);
}
After uploading image Blob to Cloud Storage , I'm getting this error ,and my image uploaded successfully
`[Unhandled promise rejection: Error: [storage/unknown] An unknown error has occurred.]
at node_modules/#react-native-firebase/storage/lib/StorageTask.js:152:22 in get__then
- ... 10 more stack frames from framework internals`
Any clue please ? Am i missing something ?
Versions
"#react-native-firebase/app": "14.7.0",
"#react-native-firebase/auth": "14.7.0",
"#react-native-firebase/firestore": "14.7.0",
"#react-native-firebase/storage": "^14.7.0",
const getPictureBlob = (uri) => {
console.log("uri", uri);
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", uri, true);
xhr.send(null);
});
};
const upload = async (
values,
formikHelpers
) => {
let blob: any;
try {
blob = await getPictureBlob(values.photo);
const ref = await storage().ref().child(currentUser.uid);
const snapshot = await ref.put(blob);
let remoteUrl = snapshot.ref.getDownloadURL();
console.log("remoteUrl", remoteUrl);
} catch (e) {
console.log("Error", e);
} finally {
blob.close();
}
};
In JS, I wanted to create a function that made a xHTMLRequest to a backend PHP server, problem is I want JS to wait for the response, otherwise it will display 'undefined'.
function xhrReq(method, args) {
let xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(args);
xhr.onreadystatechange = ()=> {
if(xhr.readyState == 4) {
return xhr.response;
}
}
How can I make this function return the response value?
You can use fetch in a async function:
(async () => {
try {
//const args = ...;
var headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");
const response = await fetch('http://localhost/example/php/example.php', {
method: 'POST', // or other
headers,
body: args
});
} catch (err) {
//process error
}
})()
or you can promisify your function :
function xhrReq(method, args) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(Error(`XHR request failed. Error code: ${xhr.statusText}`));
}
};
xhr.onerror = function() {
reject(Error('There was a network error.'));
};
xhr.send(args);
});
}
And use it in a async function (or use promise) to get the response.
I want to use a variable which has the JSON data to later parse and stringify it
all i want now is to see the actual array of objects in the console!
console.log(fetchJSON('url'));
function fetchJSON(url, cb) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status < 400) {
cb(null, xhr.response);
} else {
cb(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
}
};
xhr.onerror = () => cb(new Error('Network request failed'));
xhr.send();
}
I expect the output of console.log(fetchJSON('url'));
to be
Try this:
fetchJSON('url', function(result) {
console.log(result);
});
Your function fetchJSON is returning a callback function. If you want to return just the result change
this
cb(null, xhr.response);
to:
return xhr.response;
I come from here: How to make an AJAX call without jQuery?
And it is difficult to mock the Promise, the AJAX call or both.
I have tried so far with jasmine-ajax but it seems to have a bug... and apparently "is only meant for browser environment".
I have also tried to mock the XMLHttpRequest object but without success.
So, I am not sure what my options are here:
function get(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('GET', url);
req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
req.onerror = (e) => reject(Error(`Network Error: ${e}`));
req.send();
});
}
Proof of concept how XMLHttpRequest can be mocked
function get(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('GET', url);
req.onload = () => req.status === 200 ? resolve(req.response) : reject(Error(req.statusText));
req.onerror = (e) => reject(Error(`Network Error: ${e}`));
req.send();
});
}
describe('XMLHttpRequest', function() {
var xhr
var urls
beforeEach(() => {
xhr = {
open: (_type_, _url_) => {
xhr.status = urls[_url_].status
xhr.response = urls[_url_].response
xhr.statusText = urls[_url_].statusText
},
send: () => {
setTimeout(xhr.onload, 1)
}
}
XMLHttpRequest = jasmine.createSpy(xhr).and.returnValue(xhr)
})
it('resolves query with `response`', function(done) {
urls = {
'http://foo/bar': {
response: 'some other value',
status: 200
}
};
get('http://foo/bar')
.then(r => expect(r).toBe('some other value'), e => expect(e).toBe(undefined))
.then(done)
})
it('rejects query with `statusText`', function(done) {
urls = {
'http://baz/quux': {
response: 'some other value',
status: 500,
statusText: 'some error'
}
};
get('http://baz/quux')
.then(r => expect(r).toBe(undefined), e => expect(e.message).toBe('some error'))
.then(done)
})
})
<script src="https://safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<link href="https://safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />