Viewing firebase storage dms files - firebase

I'm on a Mac. What application can open the dms files you download directly from the console?
Preview doesn't work, and I also tried Unarchiver per the following link, but no go:
https://fileinfo.com/extension/dms

Okay, so it turns out that you only need change the extension. In my case it was from .dms to .jpg.

I think you're trying to download the Image with DownloadURL which are stored in Firebase Storage but you're getting a file with dms extension instead of actual image file. The problem is that you're not providing Content Type of Meta Data while uploading it.
By doing this, the type of the image is application/octet-stream.
Now if you download the file with Download URL, you'll get file with dms extension.
If you want to download the actual image then just add the Content Type of Meta Data and pass it in putData method.
let metaDataForImage = StorageMetadata()
metaDataForImage.contentType = “image/jpeg"
Now see the image in Firebase Storage. The type of the image is image/jpeg.
Just try downloading the image with DownloadURL. The file will be downloaded with image(jpeg) extension instead of dms extension. That's it!
Sample Code Snippet :
let metaDataForImage = StorageMetadata()
metaDataForImage.contentType = "image/jpeg"
storageRef.putData(imageData, metadata: metaDataForImage, completion: { (metadata, error) in
print("Image uploaded to Firebase successfully")
//MARK: - Uploading Image URL
self.storageRef.downloadURL(completion: { (url, error) in
if url != nil {
guard let profileImageURL = url?.absoluteString else { return }
FirebaseDatabaseReference.users(uid: userUID).reference().updateChildValues(["profileImageURL": profileImageURL], withCompletionBlock: { (error, reference) in
if error == nil {
print("URL Uploaded to Firebase DB")
} else {
print("Failed to upload Image URL to Firebase DB")
}
})
}
})
})

Related

Meteor CollectionFS / GridFS verify correct upload of a file

In our Meteor App we sometimes run into the issue, after uploading a file that the generated download link is .../null and the file is not retrievable anymore or never was uploaded correctly.
There are no errors logged at all.
FileUploads.insert(file, function (err, fileObj) {
if (err) { // this error never triggers
log(err);
} else {
if(fileObj.isUploaded()) { // is true after correct or non correct upload
FileUploads.find(fileObj._id); // fetches correct metadata even if file upload was corrupt
if(fileObj.url()=== 'null') {
throw Meteor.Error(...) // never thrown even when URL was "null"
}
}
}
List of used cfs packages:
cfs:access-point#0.1.49_2
cfs:base-package#0.0.30
cfs:collection#0.5.5
cfs:collection-filters#0.2.4
cfs:data-man#0.0.6
cfs:file#0.1.17
cfs:gridfs#0.0.34
cfs:http-methods#0.0.32
cfs:http-publish#0.0.13
cfs:power-queue#0.9.11
cfs:reactive-list#0.0.9
cfs:reactive-property#0.0.4
cfs:standard-packages#0.5.10
cfs:storage-adapter#0.2.4
cfs:tempstore#0.1.6
cfs:upload-http#0.0.20
cfs:worker#0.1.5
So how can we make sure the file was uploaded correctly right after an upload?
fileObj,isUploaded() seems not reliable. Is there a better way to verify the correct upload?

can't upload image to cloudinary from firebase cloud function

According to cloudinary's documentation one should be able to upload an image to cloudinary using google cloud storage.
However when I attempt to do so, I get the following error in my cloud functions logs.
ENOENT: no such file or directory, open 'gs://my-bucket.appspot.com/01.jpg'
this is my cloud function:
import * as functions from 'firebase-functions';
import * as cloudinary from 'cloudinary';
cloudinary.config({
cloud_name: functions.config().cloudinary.cloudname,
api_key: functions.config().cloudinary.apikey,
api_secret: functions.config().cloudinary.apisecret,
});
export const uploadImageToCloudinary = functions.storage
.object()
.onFinalize(object => {
cloudinary.v2.uploader.upload(
`gs://${object.bucket}/${object.name}`,
function(error, result) {
if (error) {
console.log(error)
return;
}
console.log(result);
}
);
})
I have added /.wellknown/cloudinary/<cloudinary_cloudname> to my bucket as well added permission in cloud platform to allow cloudinary object viewer access
Is there an extra step I'm missing - I can't seem to get this working?!
Cloudinary does support Google cloud storage upload, but it's a relatively new feature and the current version of the node SDK doesn't handle gs:// urls.
In your example, it's trying to resolve the gs:// URL on the local server and send the image to Cloudinary, rather than sending the URL to Cloudinary so the fetch happens from Cloudinary's side.
Until this is added to the SDK, you could get this working by triggering the fetch using the URL-based upload method, or by making a small change to the SDK code.
Specifically, it's a small change in lib/uploader.js - you need to add the gs: prefix there, after which it should work OK.
Diff:
diff --git a/lib/uploader.js b/lib/uploader.js
index 2f71eaa..af08e14 100644
--- a/lib/uploader.js
+++ b/lib/uploader.js
## -65,7 +65,7 ##
return call_api("upload", callback, options, function() {
var params;
params = build_upload_params(options);
- if ((file != null) && file.match(/^ftp:|^https?:|^s3:|^data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$/)) {
+ if ((file != null) && file.match(/^ftp:|^https?:|^gs:|^s3:|^data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$/)) {
return [
params, {
file: file
After applying that diff, I did successfully fetch an image from Google Cloud Storage

Alamofire v4, Swift v3 Uploading Sqlite file to domain

I’m trying to upload an Sqlite database from IOS Swift 3 to my server using Alamofire 4.0, but having problems converting the sqlite file into the data type required to upload.
The majority of posts / question examples seem to default to uploading images, but I am struggling to find example of uploading sqlite or other file types (for back-up purposes)
I have searched for the basic code and found this so far which looks very reasonable (thanks to following post: Alamofire 4 upload with parameters)
let parameters = ["file_name": "swift_file.jpeg"]
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(self.photoImageView.image!, 1)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to:"http://sample.com/upload_img.php")
{ (result) in
switch result
{
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
//Print progress
})
upload.responseJSON { response in
//print response.result
}
case .failure(let encodingError):
//print encodingError.description
}
}
The part I’m struggling with is to append the sqlite file to the upload (multipartFormData.append(………..?) I’ve searched but not found any good reference posts.
Yes, i’m a newbe, but trying hard, any help would be appreciated…..
It's exactly the same as the image example except that the mime type would be application/octet-stream.
Also, you'd probably go ahead and load it directly from the fileURL rather than loading it into a Data first.
As an aside, the parameters in that example don't quite make sense, as it looks redundant with the filename provided in the upload of the image itself. So you'd use whatever parameters your web service requires, if any. If you have no additional parameters, you'd simply omit the for (key, value) { ... } loop entirely.
Finally, obviously replace the file field name with whatever field name your web service is looking for.
// any additional parameters that must be included in the request (if any)
let parameters = ["somekey": "somevalue"]
// database to be uploaded; I'm assuming it's in Documents, but perhaps you have it elsewhere, so build the URL appropriately for where the file is
let filename = "test.sqlite"
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent(filename)
// now initiate request
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(fileURL, withName: "file", fileName: filename, mimeType: "application/octet-stream")
for (key, value) in parameters {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
}, to: urlString) { result in
switch result {
case .success(let upload, _, _):
upload
.authenticate(user: self.user, password: self.password) // only needed if you're doing server authentication
.uploadProgress { progress in
print(progress.fractionCompleted)
}
.responseJSON { response in
print("\(response.result.value)")
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
}
}
Unrelated, but if you're ever unsure as to what mime type to use, you can use this routine, which will try to determine mime type from the file extension.
/// Determine mime type on the basis of extension of a file.
///
/// This requires MobileCoreServices framework.
///
/// - parameter url: The file `URL` of the local file for which we are going to determine the mime type.
///
/// - returns: Returns the mime type if successful. Returns application/octet-stream if unable to determine mime type.
func mimeType(for url: URL) -> String {
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream";
}

React-native Firebase storage upload using putString call

I'm setting up this thread in order to clarify, whether firebase storage putString method does or does not work in React-native.
From what I've searched there is currently no way to upload File or Blob types to Firebase Storage using put method.
React Native does not support the File and Blob types, so Firebase Storage uploads will not work in this environment. File downloads do work however.
SOURCE: The Firebase Blog
Thus this call
firebase.storage().ref()
.child(userID)
.put(new File(['this is a small amount of data'], 'sample-text.txt', { type: "text/plain" }), { type: "text/plain" })
.then(p => {console.log(p)})
.catch(p => {console.log(p)})
does not work and ends up with response
code : "storage/unknown" message : "Firebase Storage: An unknown error
occurred, please check the error payload for server response." name :
"FirebaseError" serverResponse : "Multipart body does not contain 2 or
3 parts."
Nevertheless there is another option to upload data to Firebase Storage, using Firebase storage putString method. Which works with plain string. But even if I use this method to upload. I'm getting the same server reponse as before.
firebase.storage()
.ref()
.child(userID)
.putString('string')
.then(p => {console.log(p)})
.catch(p => {console.log(p)});
Bu from what I've learned from this answer. The putString way should work.
What am I doing wrong? The code works fine for me in React. Whenever I paste to React-native. It stops working.
I've just tried react-native-fetch-blob as Ven commented before, and I was able to make it work, try using this snippet from the index file in the example:
1) Before class declaration:
import RNFetchBlob from 'react-native-fetch-blob';
const Blob = RNFetchBlob.polyfill.Blob;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
2) Inside the storing method:
let filePath = 'YOUR/FILE/PATH';
let fileName = 'file_name.jpg';
let rnfbURI = RNFetchBlob.wrap(filePath);
// create Blob from file path
Blob
.build(rnfbURI, { type : 'image/png;'})
.then((blob) => {
// upload image using Firebase SDK
firebase.storage()
.ref('images')
.child(fileName)
.put(blob, { contentType : 'image/jpg' })
.then((snapshot) => {
console.log('Uploaded', snapshot.totalBytes, 'bytes.');
console.log(snapshot.metadata);
var url = snapshot.metadata.downloadURLs[0];
console.log('File available at', url);
}).catch(function(error) {
console.error('Upload failed:', error);
});

File download from API to Meteor server and upload to S3

I am sending a request from my Meteor server to download a file via an API. I then want to upload that file to S3. I keep getting the following "NoSuchKey: The specified key does not exist." I initially thought it was maybe a problem with my AcessKey/SecretKey form AWS but after googling this for a while the only examples I could find of other people getting this error is when trying to download a file from S3.
Setting up cfs:s3
var imageStore = new FS.Store.S3("images", {
accessKeyId: "MyAcessKeyId", //required if environment variables are not set
secretAccessKey: "MySecretAcessKey", //required if environment variables are not set
bucket: "BucketName", //required
});
Images = new FS.Collection("images", {
stores: [imageStore]
});
Start file transfer from API and upload to S3
client.get_result(id, Meteor.bindEnvironment(function(err, result){ //result is the download stream and id specifies which file to download.
if (err !== null){
return;
}
var file = new FS.File(result);
Images.insert(file, function (err, fileObj) {
if (err){
console.log(err);
}
});
}));
Note: I was getting the following error so I added Meteor.bindEnvironment.
"Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment."
Node.js example from API Documentation
client.get_result(id, function(err, result){
if (err != null) {
return;
}
file.writeFile(path.join('public', path.join('results', filename)), result, 'binary');
});
What ended up fixing the problem for me was moving part of the setup to the lib folder. Although I tried several different ways I was unable to get it to execute entirely on the server. It looks like the documentation was updated recently which states everything a bit more clearly. If you follow this setup it should eliminate the error. See the section titled Client, Server, and S3 credentials
https://github.com/CollectionFS/Meteor-CollectionFS/tree/master/packages/s3
Note: Make sure not to place you secret key is not in you lib folder as this is accessible from the client.

Resources