简体   繁体   English

使用 swift 将图像保存为 image/jpeg 到 firebase

[英]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.我正在尝试使用 image/jpeg 的 mime 类型将图片上传到 firebase,但由于某种原因,它们都以应用程序/八位字节流的形式上传。

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'}; 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.鉴于此,指定我们需要定义其 contentType 的文件或数据类型。 We can do it by assigning Media type, which is also known as MIME Protocol .我们可以通过分配媒体类型来实现,媒体类型也称为MIME 协议

some of the Common MIME types :一些常见的MIME 类型

Extension延期 MIME Type MIME 类型
.gif .gif image/gif图片/gif
.html .html text/html文本/html
.jpg or.jpeg .jpg 或.jpeg image/jpeg图片/jpeg
.mp4 .mp4 video/mp4视频/mp4

for list of MIME extension Link .用于 MIME 扩展链接列表。
plus as per this link application/octet-stream is the default value for media type.加上这个链接application/octet-stream是媒体类型的默认值。

Swift part: Swift部分:

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至于从 swift 使用 firebase 存储,我们可以使用 StorageMetadata class 分配元数据。Firebase 的 putData 方法有可选参数 metaData 类型StorageMetadata

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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