I'm trying to upload to my Storage bucket and then get the downloadURL to that uploaded file right after the upload is done. This was working previously but has since stopped for some reason.
My console print is just returning null. I was hoping for a solution or even a better way of doing this. Any help would be awesome!
I'm using Angular 5.
Here is my current method:
upload(event) {
this.showProgressBar = true;
const randomId = Math.random().toString(36).substring(2);
this.ref = this.afStorage.ref(randomId);
this.uploadTask = this.ref.put(event.target.files[0]);
this.uploadProgress = this.uploadTask.percentageChanges().subscribe(progress => {
console.log(progress);
document.querySelector('#progressBar').style.width = progress + "%";
if(progress === 100){
this.showProgressBar = false;
this.showUploaded = true;
this.downloadURL = this.uploadTask.downloadURL().subscribe(url => {
console.log(url);
});
}
});
}
Here is the way that I coded using angularfire 2 for the file uploading process.
public selectedFile: FileList;
chooseFile(event) {
this.selectedFile = event.target.files;
}
uploadImage() {
const file = this.selectedFile.item(0);
const key = 'uploads/' + '/' + Math.floor(Math.random() * 1000000) + file.name;
const upload = this.stroge.upload(key, file).then(() => {
const ref = this.stroge.ref(key);
const downloadURL = ref.getDownloadURL().subscribe(url => {
this.Updateprofile(url);
});
});
}
Here is the part of the component I’m using in an Ionic app to upload up to 5 pics
uploadPicture(i) {
let that=this;
this.cameraPlugin.getPicture({
quality: 100,
destinationType: this.cameraPlugin.DestinationType.DATA_URL,
sourceType: this.cameraPlugin.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: this.cameraPlugin.EncodingType.PNG,
//targetWidth: 500,
//targetHeight: 500,
saveToPhotoAlbum: true
}).then(
imageData => {
// Send the picture to Firebase Storage
const selfieRef = this.addPictureFile();
var uploadTask = selfieRef.putString(imageData, 'base64', {contentType: 'image/png'});
// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
that.uploading = true;
that.picsCtrl[i].buttonDisabled = true;
uploadTask.on('state_changed',
function(snapshot) {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (uploadTask.snapshot.bytesTransferred / uploadTask.snapshot.totalBytes) * 100;
that.loadProgress = progress;
switch (uploadTask.snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
var imageURL = selfieRef.getDownloadURL().then(url => {
that.uploading = false;
that.picsCtrl[i].imgSrc = url;
that.picsCtrl[i].buttonHidden = !that.picsCtrl[i].buttonHidden;
that.picsCtrl[i].imgHidden = !that.picsCtrl[i].imgHidden;
that.addPictureRef(url)
.then( keyRef => {
that.picsCtrl[i].imgKey = keyRef.key;
that.picsCtrl = that.createBucket(that.picsCtrl);
});
});
});
});
},
error => {
console.log(error);
}
);
}
The relevants parts of the code are:
Using that instead of this when the stream is being uploaded
The use of several vars to show the progress bar and update the progress and the final func to get the url and do some stuff in the view
In my app there’s a component that handles the process of uploading and removing images.
Related
I am trying to write a function that uploads a jpeg image to firebase storage and returns the download link of the uploaded file. But when I execute the function, the file does not completely upload to the storage i.e. original file size is 10 KB and uploaded file size is 9 B. I'm using the following code:
const storageRef = firebase.storage().ref();
const dpRef = storageRef.child("users/dp.jpg").put(file, {
contentType: "image/jpeg",
});
dpRef.on(
firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("Upload is " + progress + "% done");
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log("Upload is paused");
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log("Upload is running");
console.log(progress);
break;
default:
break;
}
},
(error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case "storage/unauthorized":
// User doesn't have permission to access the object
console.log("Unauthorized");
break;
case "storage/canceled":
// User canceled the upload
console.log("Cancelled");
break;
// ...
case "storage/unknown":
// Unknown error occurred, inspect error.serverResponse
console.log("Unknown");
break;
default:
break;
}
},
() => {
// Upload completed successfully, now we can get the download URL
dpRef.snapshot.ref.getDownloadURL().then((downloadURL) => {
console.log("File available at", downloadURL);
});
}
);
The console.log(progress) shows NaN for some reason. I also tried download
I'm not sure what is the problem, but I did this recently and I can share my code:
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/storage';
const uploadImageFetch = async (uri) => {
const blob = await 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 imageNameBefore = uri.split('/');
const imageName = imageNameBefore[imageNameBefore.length - 1];
const ref = firebase.storage().ref().child(`images/${imageName}`);
const snapshot = await ref.put(blob);
blob.close();
return await snapshot.ref.getDownloadURL();
};
This function accept a local URI with the image, and returns the download URL.
You can see more examples in the official Documentation https://firebase.google.com/docs/storage/web/upload-files
I have this code in js witch recod an audio from the browser and I need to send it back from js to flask
start: function () {
var options = {audio: true, video: false};
navigator.mediaDevices.getUserMedia(options).then(function (stream) {
myRecorder.objects.stream = stream;
myRecorder.objects.recorder = new Recorder(
myRecorder.objects.context.createMediaStreamSource(stream),
{numChannels: 1}
);
myRecorder.objects.recorder.record();
}).catch(function (err) {});
How I should do that while making the file in wav format?
The following example creates a limited time audio recording and uploads it when finished. A form containing a blob is used for this.
It would also be possible to transmit the pure blob to the server, but since there are differences in the audio format used depending on the browser, this is the more general variant.
(function() {
const uploadURL = "{{ url_for('upload') }}";
const startButton = document.getElementById("toggle-rec-btn");
startButton.addEventListener("click", function() {
if (!navigator.mediaDevices) {
console.error("getUserMedia not supported.")
return;
}
const constraints = { audio: true };
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
let chunks = []
let recorder = new MediaRecorder(stream);
recorder.ondataavailable = event => {
// Collect all the chunks of the recording in an array.
chunks.push(event.data);
};
recorder.onstop = event => {
console.log("Recording stopped.")
// Create a blob with all the chunks of the recording.
let blob = new Blob(chunks, { type: recorder.mimeType });
chunks = [];
startButton.disabled = false;
// Create form data that contain the recording.
let formData = new FormData();
formData.append("audio_file", blob);
// Send the form data to the server.
fetch(uploadURL, {
method: "POST",
cache: "no-cache",
body: formData
}).then(resp => {
if (resp.status === 200) {
window.location.reload(true);
} else {
console.error("Error:", resp)
}
}).catch(err => {
console.error(err);
});
};
recorder.onstart = event => {
console.log("Recording started.");
startButton.disabled = true;
// Stop recording when the time is up.
setTimeout(function() { recorder.stop(); }, 10000);
};
recorder.start();
})
.catch(function(err) {
console.error(err);
});
});
})();
All recordings are saved on the server in a directory with the default name "var/app-instance/uploads".
import os
from flask import abort, current_app, make_response, request
from mimetypes import guess_extension
from werkzeug.utils import secure_filename
#app.route('/upload', methods=['POST'])
def upload():
if 'audio_file' in request.files:
file = request.files['audio_file']
# Get the file suffix based on the mime type.
extname = guess_extension(file.mimetype)
if not extname:
abort(400)
# Test here for allowed file extensions.
# Generate a unique file name with the help of consecutive numbering.
i = 1
while True:
dst = os.path.join(
current_app.instance_path,
current_app.config.get('UPLOAD_FOLDER', 'uploads'),
secure_filename(f'audio_record_{i}{extname}'))
if not os.path.exists(dst): break
i += 1
# Save the file to disk.
file.save(dst)
return make_response('', 200)
abort(400)
I wish you every success in implementing your project.
I've been trying to work on this for a while. I'm working with google drive api -> and I'm trying to try to get the main script to re-run the request of the accessToken is incorrect and causes an error.
Can that be sent to the main script somehow?
Adding some code to show I've actually worked on this lol - left out some bc it's alot of other unrelated stuff.
I am using IndexedDB to pass info between SW and main Script
//////////////////////////////////////////////////////////////
//////////////// Check Database onload ///////////////////////
//////////////////////////////////////////////////////////////
window.addEventListener("load", checkUpload(), false);
function checkUpload() {
if (supportCheck()) {
let openRequest = indexedDB.open("GoogleDrive", 1);
openRequest.onsuccess = (e) => {
var db = e.target.result;
var objectStore = db
.transaction(["backups"], "readwrite")
.objectStore("backups");
var request = objectStore.get("1");
request.onerror = function () {
// Handle errors!
};
request.onsuccess = function (event) {
var data = event.target.result;
if (googleSignin.isAuthorizedForGDrive()) {
// Call SW Function
}
else {
//Google Sign in Error
}
let accessToken = gapi.auth.getToken().access_token;
data.access = accessToken;
// Put this updated object back into the database.
var requestUpdate = objectStore.put(data);
requestUpdate.onerror = function (event) {
// Do something with the error
};
requestUpdate.onsuccess = function (event) {
// Success - the data is updated!
// Call SW Function
};
}
}
}
}
}
//////////////////////////////////////////////////////////////
//////////////// Initialize Database Function ///////////////
//////////////////////////////////////////////////////////////
uploadBtn.addEventListener("click", handleUploadClick, false);
save.addEventListener("click", handleUploadClick, false);
//Adds/Create Data that is stored in IndexedDB so that the Service Worker can
access and use it
//ServiceWorker Call Function
function initSW() {
console.log("Script: Called InitSW()");
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("serviceWorker.js")
.then((registration) => navigator.serviceWorker.ready)
.then((registration) => {
registration.sync.register("sendFile-sync").then(() => {
//Do Function using sync
try {
console.log("Script : Sync Registered");
} catch {
console.log("Script : Sync Not Registered");
}
});
});
}
}
SW
self.addEventListener("sync", (e) => {
if (e.tag === "sendFile-sync") {
console.log("SW Sync : Sync Found!");
e.waitUntil(fetchFile());
} else {
console.log("SW Sync : No Sync Found");
}
});
//Function Called above when sync is fired
function fetchFile() {
let openRequest = indexedDB.open("GoogleDrive", 1);
openRequest.onerror = function () {
};
openRequest.onsuccess = function () {
let db = openRequest.result;
let transaction = db.transaction(["backups"], 'readwrite');
let backups = transaction.objectStore("backups");
let request = backups.get("1");
request.onsuccess = function (event) {
let date = Date();
let accessToken = request.result.access;
console.log("SW Sync: Access Token - " + accessToken);
let BlobContent = request.result.text;
let file = BlobContent;
let metadata = {
name: "Backup " + date, // Filename
mimeType: "application/pdf", // mimeType at Google Drive
parents: ["root"], // Root Folder ID for testing
};
let form = new FormData();
form.append(
"metadata",
new Blob([JSON.stringify(metadata)], { type: "application/json" })
);
form.append("file", file);
fetch(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id",
{
method: "POST",
headers: new Headers({ Authorization: "Bearer " + accessToken }),
body: form,
}
)
.then((res) => {
return res.json();
})
.then(function (val) {
console.log(val.error.message);
<!-- message is "invalid credentials --> in our scenario
}
})
}
request.onerror = function () {
console.log("SW Sync : Getting IndexedDB values error");
};
};
}
Sure, the ServiceWorker's clients are exposed in its self.clients property, from where you can find the correct Client with which you can communicate thanks to its postMessage() method.
How to find the correct client will depend on the situation, for instance in the install or activate events there should be only one client, so you should be able to reach it by doing
const clients = await self.clients.matchAll();
const client = clients[0];
client.postMessage("something bad happenned...");
In a fetch event, the clientId is exposed on the event instance, so you can do
const client = await self.clients.get(evt.clientId);
client.postMessage("something bad happenned...");
I must admit I don't know well the BackgroundSync API, so I'm not sure if in this sync event your page would be the only one client, however, you can certainly make your page open a private communication channel with the SW even before, which by the way, sounds like a better mean of passing your API's credentials than through IDB:
const channel = new MessageChannel();
channel.port1.onmessage = SWTalksToMe; // handle messages from SW
navigator.serviceWorker
.register("serviceWorker.js")
.then((registration) => navigator.serviceWorker.ready)
.then((registration) => {
registration.postMessage("", [channel.port2]));
return registration.sync.register("sendFile-sync")
})
//...
And in your ServiceWorker
self.addEventListener("message", evt => {
if(evt.ports) {
client_port = evt.ports[0];
}
});
Finally, if you wanted to communicate with all the clients, you could use a BroadcastChannel.
I generated pdf through nodejs. i want to add watermark to this generated pdf. I used dynamic-html-pdf plugins in my code. If there is any options for adding watermark in dynamic-html-pdf. Here i display my sample code here.
var path=require('path');
var pdf = require('dynamic-html-pdf');
var html='<!DOCTYPE html><html><head><style>';
html=html+'</style>';
html=html+'</head>';
html=html+'<body>';
html=html+'<div class="divstyle1" id="content">A computer is a device that can be instructed to carry out sequences of arithmetic or logical operations automatically via computer programming. </div>';
html=html+'</body></html>';
var options = {
format: "A4",
orientation: "portrait",
border: "10mm",
base: 'file://' + path.resolve('./public/graph') + '/'
};
var document = {
type: 'file',
template: html,
context: {
img:'./public/graph/logo.jpg'
},
path: "./public/graph/mypdf.pdf"
};
pdf.create(document, options)
.then(res => {
res.status(200).json({
message: 'pdf created'
});
})
.catch(error => {
res.status(200).json({
message: 'error'
});
});
After saving your pdf document. Use image-watermark module to append a watermark to your generated pdf.
var watermark = require('image-watermark');
watermark.embedWatermark('/path/to/your/generated/pdf', {'text' : 'sample watermark'});
After pdf is created, use this package to watermark the pdf file.
pdf-watermark
const PDFWatermark = require('pdf-watermark');
await PDFWatermark({
pdf_path: "./newsletter.pdf",
text: "Gentech", //optional
image_path: "./everest.png",
});
Another solution to add text watermark in PDF document is Aspose.PDF Cloud SDK for Node.js. It is a commercial product but provides 150 free monthly API calls.
Currently, it supports the PDF file processing from Cloud Storages: Aspose internal storage, Amazon S3, DropBox, Google Drive Storage, Google Cloud Storage, Windows Azure Storage and FTP Storage. However, we have a plan to add support to process PDF documents from the request body(stream).
P.S: I'm a developer evangelist at Aspose.
const { PdfApi } = require("asposepdfcloud");
const { TextStamp }= require("asposepdfcloud/src/models/textStamp");
const { TextState }= require("asposepdfcloud/src/models/textState");
const { HorizontalAlignment }= require("asposepdfcloud/src/models/horizontalAlignment");
const { VerticalAlignment }= require("asposepdfcloud/src/models/verticalAlignment");
const { Rotation }= require("asposepdfcloud/src/models/rotation");
// Get Client Id and Client Secret from https://dashboard.aspose.cloud/
pdfApi = new PdfApi("xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxx");
var fs = require('fs');
const name = "Test.pdf";
const pageNumber = 1;
const remoteTempFolder = "Temp";
const localTestDataFolder = "C:\\Temp";
const path = remoteTempFolder + "\\" + name;
var data = fs.readFileSync(localTestDataFolder + "\\" + name);
// Upload File
pdfApi.uploadFile(path, data).then((result) => {
console.log("Uploaded File");
}).catch(function(err) {
// Deal with an error
console.log(err);
});
// Add Text Stamp
const textState = new TextState();
textState.fontSize = 14;
textState.font = 'Arial';
const stamp = new TextStamp();
stamp.background = true;
stamp.leftMargin = 1;
stamp.rightMargin = 2;
stamp.topMargin = 3;
stamp.bottomMargin = 4;
stamp.horizontalAlignment = HorizontalAlignment.Center;
stamp.verticalAlignment = VerticalAlignment.Center;
stamp.opacity = 1;
stamp.rotate = Rotation.None;
stamp.rotateAngle = 0;
stamp.xIndent = 0;
stamp.yIndent = 0;
stamp.zoom = 1;
stamp.textAlignment = HorizontalAlignment.Center;
stamp.value = "Aspose.PDF Cloud";
stamp.textState = textState;
pdfApi.postPageTextStamps(name, pageNumber,[stamp], null, remoteTempFolder).then((result) => {
console.log(result.body.code);
}).catch(function(err) {
// Deal with an error
console.log(err);
});
//Download file
const localPath = "C:/Temp/textstamp.pdf";
pdfApi.downloadFile(path).then((result) => {
console.log(result.response.statusCode);
console.log(result.body.byteLength);
fs.writeFileSync(localPath, result.body);
console.log("File Downloaded");
}).catch(function(err) {
// Deal with an error
console.log(err);
});
Problem
I am trying to create an app with react native and firebase. One of the features I would like for this app is the ability to upload images. I am having some trouble uploading the images to firebase storage though. I am using expo's image picker to find the path of the image that the user wants to upload, but once I have the path I don't know how to convert that to something I can upload to firebase.
Can somebody help me convert the path of an image to something I can upload to firebase storage with react native?
What I've tried
I tried using:
_pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
MediaTypeOptions: 'Images',
quality: 0.4,
_uploadAsByteArray = async (pickerResultAsByteArray, progressCallback) => {
try {
var metadata = {
contentType: 'image/jpeg',
};
var storageRef = firebase.storage().ref();
var ref = storageRef.child('images/'+expoID+'/'+this.state.time)
let uploadTask = ref.put(pickerResultAsByteArray, metadata)
uploadTask.on('state_changed', function (snapshot) {
progressCallback && progressCallback(snapshot.bytesTransferred / snapshot.totalBytes)
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
}, function (error) {
console.log("in _uploadAsByteArray ", error)
}, function () {
var downloadURL = uploadTask.snapshot.downloadURL;
console.log("_uploadAsByteArray ", uploadTask.snapshot.downloadURL)
this.setState({imageUploaded:true})
});
} catch (ee) {
console.log("when trying to load _uploadAsByteArray ", ee)
}
}
convertToByteArray = (input) => {
var binary_string = this.atob(input);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes
}
atob = (input) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
}
uploadImage(bsfdata){
this.setState({imageUploaded:false})
this._uploadAsByteArray(this.convertToByteArray(bsfdata), (progress) => {
this.setState({ progress:progress })
})
}
base64:true,
});
/* if (!result.cancelled) {
this.setState({ image: result.uri });
let formData = new FormData();
formData.append('photo', {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});}*/
this.uploadImage(result.base64);
};
}
I've tried it with the commented code added, which doesn't upload anything, and I've tried it with how the code is now, which gives me the error Can currently only create a Blob from other Blobs, and the uploading progress never gets above 0%.
If you are using expo (>=26), then you can do it easily with the following lines of code.
uploadImage = async(imageUri) => {
const response = await fetch(imageUri);
const blob = await response.blob();
var ref = firebase.storage().ref().child("image.jpg");
return ref.put(blob);
}
Reference: https://youtu.be/KkZckepfm2Q
Refer this link - https://github.com/dailydrip/react-native-firebase-storage/blob/master/src/App.js#L43-L69
Following block of code is working fine.
uploadImage(uri, mime = 'application/octet-stream') {
return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
let uploadBlob = null
const imageRef = FirebaseClient.storage().ref('images').child('image_001')
fs.readFile(uploadUri, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL()
})
.then((url) => {
resolve(url)
})
.catch((error) => {
reject(error)
})
})
}
You need to install rn-fetch-blob module:
npm install --save rn-fetch-blob
Then, do the following:
import RNFetchBlob from 'rn-fetch-blob';
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
function uploadImage(path) {
const imageFile = RNFetchBlob.wrap(path);
// 'path/to/image' is where you wish to put your image in
// the database, if you would like to put it in the folder
// 'subfolder' inside 'mainFolder' and name it 'myImage', just
// replace it with 'mainFolder/subfolder/myImage'
const ref = firebase.storage().ref('path/to/image');
var uploadBlob = null;
Blob.build(imageFile, { type: 'image/jpg;' })
.then((imageBlob) => {
uploadBlob = imageBlob;
return ref.put(imageBlob, { contentType: 'image/jpg' });
})
.then(() => {
uploadBlob.close();
return ref.getDownloadURL();
})
.((url) => {
// do something with the url if you wish to
})
.catch(() => {
dispatch({
type: UPDATE_PROFILE_INFO_FAIL,
payload: 'Unable to upload profile picture, please try again'
});
});
}
Please do ask if there's any part of the code that you don't understand. To upload multiple images, simply wrap this code with a for loop. Or if you want to make sure that every image is uploaded without any error, use Promise
Not sure whom this might help, but if you're using MediaLibrary to load images from the gallery, then the uri comes in the format of uri = file:///storage/emulated/0/DCIM/Camera/filename.jpg
In this case, using fetch(uri) didn't help me get the blob.
But if you use fetch(uri.replace("file:///","file:/")) and then follow #sriteja Sugoor's answer, you'll be able to upload the file blob.
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
let uploadBlob;
await fs
.readFile(params?.file.path, 'base64')
.then((data) => {
return Blob.build(data, {type: `BASE64`});
})
.then((blob) => {
uploadBlob = blob;
console.log(uploadBlob, 'uploadBlob');
});