如何将图像发送到服务器?

时间:2018-04-11 16:24:37

标签: ios swift post upload alamofire

我正在尝试使用.post和mulitpartFormData方式将UIImage文件上传到服务器。任何人都可以查看下面的代码,并告知什么是错的?我今天试图成功上传图像文件一整天。 但凭借我对swift的短暂经验和研究,即使研究与我的情况相关的正确答案也是如此困难。

PS。 “UIImageView.image必须仅从主线程使用”消息不断显示“警卫让”点。请让我借鉴你的智慧。

    Alamofire.upload(
            multipartFormData: { multipartform in
                guard let image = self.profileImage.image else { return }
                    let imageData = UIImageJPEGRepresentation(image, 0.1)
                    multipartform.append(imageData!, withName: "img_profile", mimeType: "image/jpg")

        },
            to: urlString,
            method: .post,
            encodingCompletion: { result in
                switch result {
                case .success(let request, _, _):
                    request.responseData(completionHandler: { (response) in
                        switch response.result {
                        case .success:
                            print(response)
                        case .failure(let error):
                            print(error)
                        }
                })
                case .failure(let error):
                    print(error)
                }
        })

1 个答案:

答案 0 :(得分:0)

您的问题在于以下行,因为您没有添加filename,而filename将是服务器期望图片的参数名称:

multipartform.append(imageData!, withName: "img_profile", mimeType: "image/jpg")

尝试添加文件名

进行更新
multipartFormData.append(imageData!, withName: "img_profile", fileName: "file-name", mimeType: "image/jpg")

希望这会有所帮助。