can't upload images via FileTransfer plugin of ionic 3 to Cloudinary - ionic-framework

I'm trying to upload images from mobile gallery to cloudinary.
I have followed the logic in documentation of uploading photos from angular to cloudinary that I found in this link.
And I used File Transfer plugin to upload photos from ionic3 app to cloudinary.
this is the upload() function :
upload() {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'testName',
fileName: 'test',
mimeType : "text/plain",
headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
params:{upload_preset:'preset'}
};
let url = 'https://api.cloudinary.com/v1_1/<cloud_name>/image/upload';
if (this.imageURI) {
fileTransfer.upload(this.imageURI[0], encodeURI(url), options)
.then((data) => {
console.log('uploaded heeere data', JSON.stringify(data))
}, (err) => {
console.log('errorrrr', JSON.stringify(err))
})
}
}
this.imageUri[0] is a photo as base 64
and in app.module.ts I have specified the cloudinary configuration :
import { CloudinaryConfiguration, CloudinaryModule } from "#cloudinary/angular-5.x";
import { Cloudinary } from "cloudinary-core";
#NgModule({
declarations: [....],
imports: [
BrowserModule,
HttpClientModule,
CloudinaryModule.forRoot({Cloudinary}, {
cloud_name: "<cloud_name>",
upload_preset: 'preset',
api_key:'<api_key>'
} as CloudinaryConfiguration),
]
.......
})
But I failed to upload.
There's no error shown.. Just a message: File Name is too long
I don't know if the connection is established or not and is it cloudinary who's refusing files with long names or what?
Could some one please help me how to debug to see where the problem is? or could someone help me fixing this?
Thanks a lot.

you should send image name not base64 encode ,the server read the base64 as name file ,so you try should send file name in first parameter

Related

Firebase hosting file upload via REST with Apps Script

I want to upload a file to Firebase hosting file upload via REST with Apps Script. Been trying to find a solution for days to no avail :( would highly appreciate any recommendations.
I'm following the official documentation here:
https://firebase.google.com/docs/reference/hosting/rest/v1beta1/sites.versions/populateFiles
And I can successfully get the upload URL using this code:
function getUploadURL() {
const YOUR_PROJECT_ID = 'sites/url-shortener-e42ec/versions/dd393a80797d713d';
let postUrl = 'https://firebasehosting.googleapis.com/v1beta1/YOUR_PROJECT_ID:populateFiles';
postUrl = postUrl.replace('YOUR_PROJECT_ID', YOUR_PROJECT_ID);
const options = {
method: 'post',
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
},
muteHttpExceptions: true
};
const response = UrlFetchApp.fetch(postUrl, options);
Logger.log(response);
}
which returns the following:
{
"uploadUrl": "https://upload-firebasehosting.googleapis.com/upload/sites/url-shortener-e42ec/versions/dd393a80797d713d/files"
}
And this is where I get kinda lost because I'm not quite sure on what to do next. The documentation says:
map (key: string, value: string)
A set of file paths to the hashes corresponding to assets that should be added to the version.
A file path to an empty hash will remove the path from the version.
Calculate a hash by Gzipping the file then taking the SHA256 hash of the newly compressed file.
But if I add a payload with a file hash to the call like so:
{
"files": {
"/teste": "3f0749957a1c4d91ed18b8e9df122709974e4e9c94c57f9245794c21dd76d4bd"
}
}
...then I get the error:
{
"error": {
"code": 400,
"message": "Precondition check failed.",
"status": "FAILED_PRECONDITION"
}
}
PART 2 :
The next issue I found is, now that I have the upload URL, I will need to actually upload the file, and according to their documentation I should:
Perform a multipart POST of the Gzipped file contents to the URL using a forward slash and the hash of the file appended to the end.
which I tried with the following apps script code:
function convert(hash) {
return hash.map(byte => ('0' + (byte & 0xFF).toString(16)).slice(-2)).join('');
}
function postFile() {
var files = DriveApp.getFilesByName('abc.txt');
let gzip;
let hash;
if (files.hasNext()) {
var file = files.next();
gzip = Utilities.gzip(file.getBlob());
hash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, gzip.getBytes());
}
let postUrl = 'https://upload-firebasehosting.googleapis.com/upload/sites/url-shortener-e42ec/versions/dd393a80797d713d/files/' + convert(hash);
/*
var textBlob = Utilities.newBlob("abc");
const gzip = Utilities.gzip(textBlob);
const hash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, gzipFile.getBytes());
*/
const data = {
"files": {
"/test.txt": convert(hash)
}
};
const options = {
method: 'post',
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
accept: 'application/json',
contentType: 'application/json'
},
muteHttpExceptions: true,
payload: JSON.stringify(data)
};
const response = UrlFetchApp.fetch(postUrl, options);
Logger.log(response);
}
... and get the following error:
Couldn't process request (status=412): File url-shortener-e42ec/dd393a80797d713d/0b3b82379e00a1994a46452e8cfd8b2c43ee8599f169a9ee4176253f1a8de469 can't be uploaded.
Appreciate all the help I can get. Thanks in advance!

upload files with ionic file transfer

Hello I would like to know if someone can help me, I want to upload files to my server on localhost with ionic using filetransfer, I have no idea how to do it. Can somebody help me? Thanks.
In the preferred Pdfs, but it can be any type of files
First you need to select a file (an image from your gallery, or a pdf as you say). Then having the path to that file:
const fileTransfer: FileTransferObject = this.transfer.create();
const options: FileUploadOptions = {
fileKey: 'file',
fileName: 'uploadfile', // Name received in the server,
mimeType: 'image/jpeg', // or application/pdf for pdf
headers: {...} // (Optional) if needed
};
fileTransfer.upload( filename, url, options ).then( response => {
// Response here
}).catch(err => {
// Error here
});
Filename is the path to the file in your device (the selected pdf file) and url is the url to your server where you are uploading.

Uploading to Google cloud storage signed url from client

I have generated a signed url from the google cloud storage that works fine when I upload files via postman, but it is impossible to upload a file from the client. I have tried everything: fetch, axios, xmlRequest––you name it. Please help me out
const files = Array.from(event.target.files)
const file:any = files[0]
const {data: {signedUrl}} = await axios.get('https://localhost:3000/signedUrlUpload')
try {
const resp = await fetch(signedUrl, {
method: 'PUT',
body: file,
headers: {
'Content-Type': 'audio/wave'
}
})
console.log(resp);
} catch (e) {
console.error(e);
}
Error: TypeError: Failed to fetch

Upload image from data url to Axios?

Ive been uploading image files to an API (Graphcool) with this, and everything was working fine:
fileUpload(file) {
let data = new FormData();
data.append('data', file);
axios
.post(`https://api.graph.cool/file/v1/MY-PROJECTID`, data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(res => {
console.log(res)
});
}
In the code above the file was passed from a <input type="file" />
However now I'm using React Avatar Editor to allow users to crop images and ensure they are a square:
https://github.com/mosch/react-avatar-editor
When you access the image from React Avatar Editor it comes in the form of a data url (via Canvas.toDataURL()).
How can I upload a data url with Axios? Do I need to first convert the image to an actual 'file' in the browsers memory?
This is a duplicate of below thread just in a different language
Sending canvas.toDataURL() as FormData
You need to change your code like below
function fileUpload(canvas) {
let data = new FormData();
canvas.toBlob(function (blob) {
data.append('data', blob);
axios
.post(`https://api.graph.cool/file/v1/MY-PROJECTID`, data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(res => {
console.log(res)
});
});
}

File upload in ionic (image or any file)?

can any one please sort it out it gives error FileTransfer is not defined.
Below is my code
controller("ExampleController", function($scope, $cordovaFileTransfer) {
$scope.upload = function() {
var options = {
fileKey: "avatar",
fileName: "yedu.jpg",
chunkedMode: false,
mimeType: "image/jpg"
};
$cordovaFileTransfer.upload("http://192.168.1.109/uploads/upload", "/android_asset/www/img/yedu.jpg", options).then(function(result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function(err) {
console.log("ERROR: " + JSON.stringify(err));
}, function (progress) {
// constant progress updates
});
}
});
I think you getting error in browser . As per the official documentation of plugin this plugin is not supported to browser for more details go to here and here.
If you testing in browser then before installing app in device add the cordovaFileTransfer plugin to your project.
cordova plugin add org.apache.cordova.file-transfer
And for the full implementation of file upload and download with cordova you may go to here.