1

我必须上传图片、音频、文件。我正在使用 Alamofire 上传。所有内容都已上传,包括截图等图库图像,但从相机拍摄的照片未上传。这是我的代码:

func requestUploadFileWithMultipart(connectionUrl: String, param : [String: AnyObject], filePath: String?, _ callBack: @escaping (_ data: DataResponse<Any>?, _ error:Error?) -> Void) {

    let URLString  = MainURL + connectionUrl

    Alamofire.upload(multipartFormData: { multipartFormData in
        for (key, value) in param {
            let stringValue = "\(value)"
            multipartFormData.append(stringValue.data(using: String.Encoding.utf8)!, withName: key)
            print("Key: \(key), Value: \(stringValue)")
        }

        if filePath != "" {
            do {
                var fileData = try Data(contentsOf: URL(string: filePath!)!)
                let ext = URL(fileURLWithPath: filePath!).lastPathComponent.components(separatedBy: ".").last
                let mime = filePath?.mimeTypeForPath()
                let fileName = "\(Date().timeIntervalSince1970)".components(separatedBy: ".").first
                multipartFormData.append(fileData, withName: "file", fileName: "\(fileName ?? "file").\(ext ?? "")", mimeType: mime ?? "")
            } catch {
                print("error loading file in multipart")
            }
        }

    }, to:URLString) { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in
                print(response.result.value as Any)



                callBack(response, nil)
            }

        case .failure(let encodingError):
            print(encodingError)

            callBack(nil, encodingError)
        }
    }
}
4

2 回答 2

1

图像压缩对我有用。可能是大文件没有上传。

于 2019-07-16T07:21:06.797 回答
0

请尝试以下代码,我在我的一个项目中使用此代码。但请确保 API 适合分段上传。

Alamofire.upload(multipartFormData: {
        multipartFormData in
        if let img =  image {
            if let imageData = img.jpegData(compressionQuality: 0.4) {
                multipartFormData.append(imageData, withName: "cmt_img", fileName: "\(Date()).jpg", mimeType: "image/jpg")
            }
        }
        do {

            let theJSONData = try JSONSerialization.data(withJSONObject: param, options: JSONSerialization.WritingOptions(rawValue: 0))
            multipartFormData.append(theJSONData, withName: "data")
        } catch {}
    },usingThreshold: 0 ,to: baseURL + URLS.AddComment.rawValue, headers: appDelegate.headers, encodingCompletion: {
        encodingResult in switch encodingResult {

        case .success(let upload, _, _):
            upload.responseObject(completionHandler: { (response: DataResponse<AddCommentData>) in

                SVProgressHUD.dismiss()
                if (response.result.value != nil) {
                    showAlert(popUpMessage.uploadingSuccess.rawValue)
                }
                else {
                    showAlert(popUpMessage.someWrong.rawValue)
                }
            })

            break

        case .failure(let encodingError):
            SVProgressHUD.dismiss()
            print(encodingError)
            break
        }
    })
}
于 2019-07-12T10:34:55.243 回答