upload image using file transfer in ionic 3 works fine on android,
but give me error on iOS when try it in simulator ..
* this is the error:
My Ionic Code:
chooseImageFromGallery()
{
this.type="0"
const options: CameraOptions = {
quality: 60,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum:true,
sourceType:0
}
this.camera.getPicture(options)
.then((imageData) => {
if (this.platform.is('ios'))
{
this.base64Image = imageData;
}
else
{
this.base64Image = imageData;
}
this.uploadimage(); // this function to upload img to server
},
(err) => {
}).then((path)=>{
})
}
uploadimage(){
this.photoSrc="";
this.translate.get("uploading Image...").subscribe(
value => {
this.sucesss=false
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: "file",
fileName:'test',
chunkedMode:false,
mimeType:"image/jpeg",
headers:{
Connection:"close"
},
httpMethod: "POST",
}
//------------ android ------------//
this.base64Image =this.base64Image
//------------ ios ------------//
//this.base64Image =this.base64Image.substring(28)
fileTransfer.upload(this.base64Image,encodeURI('mydomain/api/Product/upload'), options)
.then((data:any) => {
alert("upload success ")
}, (err) => {
this.translate.get( "error in upload Data").subscribe(
value => {
this.service.presentToast(value,2000)
}
)
})
})
}
using asp.net api2 .. My server Code :
[HttpPost]
[Route("upload")]
[AllowAnonymous]
public HttpResponseMessage uploadImage()
{
var request = HttpContext.Current.Request;
if (Request.Content.IsMimeMultipartContent())
{
foreach (string file in request.Files)
{
var postedFile = request.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
string root = HttpContext.Current.Server.MapPath("~/ServerImg");
root = root + "/" + postedFile.FileName;
postedFile.SaveAs(root);
//Save post to DB
return Request.CreateResponse(HttpStatusCode.Found, new
{
error = false,
status = "created",
path = root
});
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound, new
{
error = true
});
}
// var title = request.Params["title"];
}
// }
return null;
}
else
{
return Request.CreateResponse(HttpStatusCode.Forbidden, new
{
error = true
});
}
}
I spend more than 4 days.. but nothing is work for me ..
And this code works fine on Android but not iOS I don't know what's the wrong, I tried real iPhone and Xcode simulator and not worked
always upload error {"code":3... "http_status":500,..
Can anyone Help me please...
Related
audioData: undefined,
errorDetails: "Unable to contact server. StatusCode: 500,
ErrorDetails: "Unable to contact server. StatusCode: 500, undefin…external_ocsp_ocsp.Agent is not a constructor",
//code
synthesizeSpeech() {
let that = this;
const speechConfig = SpeechConfig.fromSubscription(
"********",
"********"
);
speechConfig.speechSynthesisLanguage = "zh-CN";
const synthesizer = new SpeechSynthesizer(speechConfig);
var soundContext = undefined;
try {
var AudioContext = window.AudioContext ||window.webkitAudioContext || false;
if(AudioContext){
soundContext = new AudioContext();
}
} catch (err) {
console.log(err)
}
synthesizer.speakTextAsync(
"你好你好你好你好你好你好你好.",
result => {
console.log(result)
if(result.audioData && soundContext){
var source = soundContext.createBufferSource();
soundContext.decodeAudioData(result.audioData,function(newBuffer){
source.buffer = newBuffer;
source.connect(soundContext.destination);
source.start(0);
})
}
synthesizer.close();
},
error => {
console.log(error);
synthesizer.close();
}
);
},
This is fixed in Microsoft Azure Cognitive Services Speech SDK for JavaScript v1.12, which will be released recently. You can download the compiled js file after the release or you can compile it from the master of the sdk repo.
Code to generate keys : Ps validPublicKey is a firebase code p256dh.
I don´t know where is the problem. If is in the generate code, or the send notification.
I need to put it in php code yet.
navigator.serviceWorker.ready
.then(function(swreg) {
reg = swreg;
console.log(swreg.pushManager.getSubscription());
console.log(JSON.stringify(swreg.pushManager.getSubscription()));
return swreg.pushManager.getSubscription();
})
.then(function(sub) {
if (sub === null) {
console.log('criando a chave');
var validPublicKey = 'BIG2EEduGTIoAYMFC3zpq2lksUw-OLRUrq_abhLs1Y2Zbo_xDUGwlozyezbSKqNkYylNN2yWKV5adB0819nQ1y0';
var convertValidPublicKey = urlBase64ToUint8Array(validPublicKey);
return reg.pushManager.subscribe({
userVisibleOnly:true,
applicationServerKey:convertValidPublicKey
});
} else {
//we have
}
}).then(function(newSub) {
return fetch('https://???????.firebaseio.com/subscriptions.json', {
method:'POST',
headers: {
'Content-Type':'application/json',
'Accept':'application/json'
},
body:JSON.stringify(newSub)
})
}).then(function(res) {
if (res.ok) {
displayConfirmNotification();
}
}).catch(function(err) {
console.log(err);
});
}
I successfully uploaded the image to firebase storage but I'm having trouble to store image url in firestore.
I received an error on console when trying to view the image:
core.js:6462 WARNING: sanitizing unsafe URL value
C:\fakepath\coke.jpg (see http://g.co/ng/security#xss)
GET unsafe:C:\fakepath\coke.jpg net::ERR_UNKNOWN_URL_SCHEME
Below is the html code: (details.page.html)
<!-- PRODUCT PICTURE INPUT -->
<ion-item>
<ion-label position="stacked">Product Picture</ion-label>
<ion-input accept="image/*" type="file" name="productPics" formControlName="productPics" (change)="showPreview($event)"></ion-input>
</ion-item>
Below is the typescript code: (details.page.ts)
ngOnInit() {
this.productForm = this.fb.group({
productPics: new FormControl('', Validators.compose([
Validators.required,
])),
});
this.resetForm();
}
showPreview(event: any) {
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.onload = (e: any) => this.imgSrc = e.target.result;
reader.readAsDataURL(event.target.files[0]);
this.selectedImage = event.target.files[0];
} else {
this.imgSrc = "./assets/default_image.jpg";
this.selectedImage = null;
}
}
async saveProduct(formValue) {
this.isSubmitted = true;
this.product.userId = this.authService.getAuth().currentUser.uid;
if (this.productId) {
try {
this.product.createdAt = new Date().getTime();
console.log('product add');
console.log(this.productForm.value);
var filePath = `${formValue.productCategory}/${this.selectedImage.name}${new Date().getTime()}`;
const fileRef = this.storage.ref(filePath);
this.storage.upload(filePath, this.selectedImage).snapshotChanges().pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe((url) => {
formValue['productPics'] = url;
this.service.insertImageDetails(formValue);
this.resetForm();
})
})
).subscribe();
await this.productService.addProduct(this.product);
await this.loading.dismiss();
this.navCtrl.navigateBack('/vendor-tabs/home-vendor');
} catch (error) {
console.log('product dont add');
this.presentToast('Error trying to save');
}
}
}
Below is the service: (product.service.ts)
private productsCollection: AngularFirestoreCollection<Product>;
addProduct(product: Product) {
return this.productsCollection.add(product);
}
getProduct(id: string) {
return this.productsCollection.doc<Product>(id).valueChanges();
}
updateProduct(id: string, product: Product) {
return this.productsCollection.doc<Product>(id).update(product);
}
deleteProduct(id: string) {
return this.productsCollection.doc(id).delete();
}
insertImageDetails(image) {
this.productsCollection.add(image);
}
What I'm trying to do:
Generate invoice using a third party lib.
Download/View invoice
My code
let createPdf = functions.https.onRequest(async (request, response) => {
// more code here
if (download == 'true') {
return response.status(200).download(__dirname + "/docs/" + newFileName, newFileName, (err) => {
if (err) {
console.log(err.message);
} else {
console.log("Downloaded:", filename)
}
})
} else {
var options = {
root: __dirname,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
return response.status(200).sendFile("/docs/" + newFileName, options, (err) => {
if (err) {
console.log(err);
} else {
console.log('Sent:', filename);
}
});
}
});
The error
{
"error": {
"code": 500,
"status": "INTERNAL",
"message": "function crashed",
"errors": [
"socket hang up"
]
}
}
Note:
When I return a simple string instead of the file it works.
Use express request and response objects to send a file.
Read this documentation: using_express_request_and_response_objects
And don't forget to use absolute path when using sendFile
How can I get photo src, from nativescript camera module?
public takePicture() {
cameraModule.takePicture().then(function(picture) {
console.log("Result is an image source instance");
var image = new imageModule.Image();
image.imageSource = picture;
console.dir(picture);
});
}
console.dir output:
=== dump(): dumping members ===
{
"android": {
"constructor": "constructor()function () { [native code] }"
}
}
=== dump(): dumping function and properties names ===
loadFromResource()
fromResource()
loadFromFile()
fromFile()
loadFromData()
fromData()
loadFromBase64()
fromBase64()
setNativeSource()
saveToFile()
height: 480
width: 640
=== dump(): finished ===
How do I get the image src ?
I want to upload it to firebase, so i need the src.
To upload to firebase, you need to upload the image via its path:
let imgsrc = this.imageSource.fromNativeSource(data);
let path = this.utils.documentsPath(randomName);
imgsrc.saveToFile(path, this.enums.ImageFormat.png);
this.firebase.uploadFile(path).then((uploadedFile: any) => {
this.appSettings.setString("fileName", uploadedFile.name);
this.router.navigate(['/soundcloud']);
this.LoadingIndicator.hide();
}, (error: any) => {
alert("File upload error: " + error);
});
}, (err: any) => {
alert(err);
});
Figured it out, this works:
public takePicture() {
cameraModule.takePicture().then((picture) => {
var image = new imageModule.Image();
image.imageSource = picture;
let savePath = fs.knownFolders.documents().path;
let fileName = 'img_' + new Date().getTime() + '_' + this.currentUserId.getValue() + '.' + enumsModule.ImageFormat.jpeg;
let filePath = fs.path.join( savePath, fileName );
picture.saveToFile(filePath, enumsModule.ImageFormat.jpeg);
this.photoService.uploadImage(filePath, fileName).then((data) => {
this._router.navigate(["/upload", fileName, this.currentUserId.getValue()]);
});
});
}