简体   繁体   中英

Save image to firebase as image/jpeg using swift

I'm trying to upload pictures to firebase with a mime type of image/jpeg but for some reason they all upload as application/octet-stream.

Heres my code snippet:

let storageRef = Storage.storage().reference().child("ProfilePictures/\(image).jpg")
        if let uploadData = UIImageJPEGRepresentation(self.pickedImage!, 0.5){
            storageRef.putData(uploadData, metadata: nil, completion:{ (metadata, error) in })

I got the image through a picker from the photo gallery

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {

        ImageButton.setBackgroundImage(editedImage, for: .normal)
        ImageButton.setTitle("", for: .normal)
        self.pickedImage = editedImage
    }

    dismiss(animated: true, completion: nil)
}

You have to set the metadata for the same.

Try it.

metadata = { contentType: 'image/jpeg'};

let imageNode = storageRef.child("imagePath/\(UUID().uuidString)")
let metaData = StorageMetadata()
metaData.contentType = "image/jpeg"
imageNode.putData(data, metadata: metaData) { (_, _) in
}

explanation:

if we upload file data without any meta data, it will recognise it as an application/octet-stream. because of data's unknown format or (missing extension), it saved as binary file which is octet-stream file.

Given that, specify file or data type we need to define its contentType. We can do it by assigning Media type, which is also known as MIME Protocol .

some of the Common MIME types :

Extension MIME Type
.gif image/gif
.html text/html
.jpg or.jpeg image/jpeg
.mp4 video/mp4

for list of MIME extension Link .
plus as per this link application/octet-stream is the default value for media type.

Swift part:

as for using firebase storage from swift, we can assign meta data using StorageMetadata class. Firebase's putData method has optional parameter metaData of type StorageMetadata

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM