简体   繁体   English

我想使用 alamofire swift 5 将图像上传到多部分表单数据

[英]I want to upload image to multipart form data using alamofire swift 5

I want to upload png image to URL like postman, i used postman postman screenshot我想像邮递员一样将 png 图像上传到 URL,我使用邮递员邮递员截图

I used this function to upload png image to url using post method using Alamofire this is upload function, but it return error code 500 Internal server error although it success with code 200 in postman我使用此功能使用 Alamofire 使用 post 方法将 png 图像上传到 url 这是上传功能,但它返回错误代码 500 内部服务器错误,尽管它在邮递员中成功使用代码 200

 static func updateProfileImage(image : UIImage , result : @escaping()->()) {

        if let user = UserDefaults.standard.string(forKey: "mail") , let imgData = image.pngData(){
            Alamofire.upload(
                multipartFormData: { multipartFormData in

                multipartFormData.append("form-data".data(using: .utf8 ,allowLossyConversion: false)!, withName: "Content-Disposition")
                //multipartFormData.append("name".data(using: .utf8 ,allowLossyConversion: false)!, withName: "fileUpload")
        multipartFormData.append(imgData, withName: "fileUpload", mimeType: "image/png")
        },
                to: URLs.profileImage+user,method: .post,
                encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let upload, _, _):
                        upload.response { response in
                            print(response)
                        }
                    case .failure( _):
                        print("error")
                    }
                }
            )
        }

I have code of multipart data request follows, I hope this will help you.我有下面的多部分数据请求代码,希望对您有所帮助。

    Alamofire.upload( multipartFormData: { multipartFormData in

        // parameters is method arguments in my webs ervice call method
        for (key, value) in parameters {
            if let data = (value as! String).data(using: .utf8) {
                multipartFormData.append(data, withName: key)
            }
        }

        let imageData = image?.jpegData(compressionQuality: 0.5)

        multipartFormData.append(imageData!, withName: "profile_image", fileName: "profileImage", mimeType: "image/jpeg")

    // getURL(.addProfile) will create url, method from my structure
    // getHeaders() will return required header from that method
    }, to: getURL(.addProfile), headers: getHeaders(), encodingCompletion: { encodingResult in

        switch encodingResult {

        case .success(let upload, _, _):

            upload.response(completionHandler: { (defaultDataResponse) in

                guard let httpResponse = defaultDataResponse.response else {
                    completion(nil, defaultDataResponse.error)
                    return
                }

                if httpResponse.statusCode == 200 {

                    // Success Code

                } else {
                    // Failed code
                }
            })

        case .failure(let encodingError):

            // Failed code.
        }
    })

Try this试试这个

func generateBoundary() -> String {
    return "Boundary-\(NSUUID().uuidString)"
}

//Set Headers with required auth //设置需要授权的标题

let boundary = generateBoundary()

let headers = ["content-type": "multipart/form-data; boundary=\(boundary)",
              "Content-Type": "application/json",
              "cache-control": "no-cache"]

//Api Call

Alamofire.upload(multipartFormData:{ multipartFormData in

            if let image = imageData {
                multipartFormData.append(image, withName: "<param_key>", fileName: objIdentityDetails.fileName ?? (String(Date().timeIntervalSince1970) + ".jpeg"), mimeType: "image/jpeg")
            }
            for (key, value) in parameters {
                multipartFormData.append(value?.data(using: String.Encoding.utf8) ?? Data(), withName: key)
            }},
                         usingThreshold:UInt64.init(),
                         to: try! <URL>,
                         method: .post,
                         headers: headers,
                         encodingCompletion: { encodingResult in
                            switch encodingResult {
                            case .success(let upload, _, _):
                                upload.responseObject { (response: <model>) in
                                    switch response.result {
                                    case .failure (let error):
                                        //Error 
                                    case .success (let responseObject):
                                       //response
                                    }
                                }
                            case .failure(let encodingError):
                                //Error 
                            }
        })

You can use this following code to upload:您可以使用以下代码上传:


Alamofire.upload(multipartFormData:{ multipartFormData in  multipartFormData.append(img, withName: "image", fileName: "image.png", mimeType: "image/png")  },

"img" - Is Your Image Data & "withName" - Is Your Name In Postman & "fileName" - Your Image Name Which You Want To Upload "img" - 是你的图像数据 & "withName" - 是你在 Postman 中的名字 & "fileName" - 你要上传的图像名称

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

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