ios10 swift3.0 Alamofire上传图片出现错误

标签 ios swift alamofire

这是我的代码。我想使用 Alamofire 上传图像

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let imagePost = info[UIImagePickerControllerOriginalImage] as? UIImage {
        let image = imagePost
        // transform image into NSData
        let data = UIImageJPEGRepresentation(image, 0.5)
        // Home path
        let homeDirectory = NSHomeDirectory()
        let documentPath = homeDirectory + "/Documents"

        let fileManager: FileManager = FileManager.default

        do {
            try fileManager.createDirectory(atPath: documentPath, withIntermediateDirectories: true, attributes: nil)
        }
        catch let error {
            print (error)
        }
        fileManager.createFile(atPath: documentPath.appending("/image.png"), contents: data, attributes: nil)
        let filePath: String = String(format: "%@%@", documentPath, "/image.png")
        print("filePath:" + filePath)
        // Alamofire upload
        Alamofire.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(filePath.data(using: .utf8)!, withName: "head_picture")
        }, to: URL, encodingCompletion: { response in
            picker.dismiss(animated: true, completion: nil)
            print(response)
            switch response {
            case .success(let upload, _, _):
                    upload.responseString(completionHandler: { (response) in
                        print("Success")
                        print(response)
                        print("Success")
                        self.portraitUIImageView.image = UIImage(data: data!)
                    })
            case .failure(let encodingError):
                print("error")
                print(encodingError)
            }
        })
    }
    else {
        print ("有错误")
    }
}

我这样打印我的请求,url部分被隐藏

> success(request: $ curl -i \
-X POST \
-b "JSESSIONID=B4148AC39E35C599773A9A86DAE8D19F" \
-H "Content-Type: multipart/form-data; boundary=alamofire.boundary.74e3ed8f93ce9353" \
-H "Accept-Language: zh-Hans-US;q=1.0, en;q=0.9" \
-H "User-Agent: OldFriend/1.0 (MichaelHuang.OldFriend; build:1; iOS 10.3.0) Alamofire/4.4.0" \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
"http://***.**.***.200:9999/upload/head-picture.do", streamingFromDisk: false, streamFileURL: nil)

我想使用Alamofire4.0将头像上传到我的服务器。现在我收到这样的错误。我从服务器收到消息说我需要提供 MultipartFile 参数“head_picture”。但我确实提供了它,我该如何修复它?

success SUCCESS: HTTP Status 400 – Bad Requesth1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}

HTTP Status 400 – Bad Request

Type Status Report

Message Required MultipartFile parameter 'head_picture' is not present

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Apache Tomcat/9.0.0.M18

success

最佳答案

我已经使用 Alamofire 成功上传了图像,但我的做法完全不同:

更改此代码:

    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(filePath.data(using: .utf8)!, withName: "head_picture")
    }, to: URL, encodingCompletion: { response in
        picker.dismiss(animated: true, completion: nil)
        print(response)
        switch response {
        case .success(let upload, _, _):
                upload.responseString(completionHandler: { (response) in
                    print("Success")
                    print(response)
                    print("Success")
                    self.portraitUIImageView.image = UIImage(data: data!)
                })
        case .failure(let encodingError):
            print("error")
            print(encodingError)
        }
    })

喜欢这个:

    let req = Alamofire.upload(data, to: URL, method: HTTPMethod.put, headers: nil)
    req.response { (response: DefaultDataResponse) in
        print(response)
    }

您可以尝试使用其他方法,例如 post,并根据需要发送 header 。 希望对您有帮助。

关于ios10 swift3.0 Alamofire上传图片出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43750070/

相关文章:

objective-c - iOS 通过应用内购买从服务器下载非消耗性内容

swift - 设置注释时获取nil。映射项的值,mapkit swift 4

ios - SwiftyJSON : Update Cells in UITableView from JSON response

swift2 - 带有 Swift 2.0 的 Alamofire Manager 被取消

ios - 在 Uitableview 中显示 Sqlite 数据

ios - 存折在特定时间提醒我

ios - 代码 : Stack View Move to next line if screen is too small

ios - 使用 NSPredicate 在自定义对象的 NSArray 中搜索字符串

ios - 检查应用程序是否由于 RemoteNotification 而变得事件(应用程序已启动)

ios - Alamofire - 如何获取表中的记录数