使用Alamofire快速上传带有参数的图像

问题描述 投票:0回答:1

我想从图库中上传图片,但显示出这样的错误

我的代码是这样的

func groupProfile(completion:@escaping CompletionHandler){

    let imageSource = pickedImage.jpegData(compressionQuality: 1.0)
    let parameters = ["filename": imageSource]

    let headers : HTTPHeaders = [
        "token" : AuthServices.instance.authToken,
        "Content-type": "multipart/form-data",
        "Content-Disposition" : "form-data"
    ]
    AF.upload(multipartFormData: { multipartFormData in
          multipartFormData.append(imageSource!, withName: "filename",fileName: "Avatar.jpeg" , mimeType: "image/png")
            for (key, value) in parameters
            {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        let jpegData = self.pickedImage.jpegData(compressionQuality: 1.0)
            multipartFormData.append(Data((jpegData)!), withName: "filename")

    }, to: SAVE_IMAGE_ON_SERVER_URL,method: .put,headers: headers)

        .response { response in
            debugPrint(response)
    }

}
swift alamofire
1个回答
0
投票

我认为您只需添加multipartFormData.append(imageSource!, withName: "filename",fileName: "Avatar.jpeg" , mimeType: "image/png"),将mimeType更改为“ image / jpeg”,并删除以下几行,因为它试图重复相同的逻辑。]

           for (key, value) in parameters
            {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        let jpegData = self.pickedImage.jpegData(compressionQuality: 1.0)
            multipartFormData.append(Data((jpegData)!), withName: "filename")

我已经格式化为应上传图像的代码,以达到您想要的目的。

func groupProfile(completion:@escaping CompletionHandler){

    guard let imageData = pickedImage.jpegData(compressionQuality: 1.0) else{
        return
    }

    let headers : HTTPHeaders = [
        "token" : AuthServices.instance.authToken,
        "Content-type": "multipart/form-data",
        "Content-Disposition" : "form-data"
    ]

    let upload:(MultipartFormData)->Void = { multidata in
        multidata.append(imageData, withName: "filename", fileName: "Avatar.jpg", mimeType: "image/jpeg")
    }

    Alamofire.upload(multipartFormData: upload,
                to: SAVE_IMAGE_ON_SERVER_URL,
                method: .post,
                headers: headers){ response in

        debugPrint(response)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.