作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要帮助使用 alamofire 5 将视频上传到我的服务器
1 Multiple images uploaded successfully with this code.
2 I am using
TLPHAsset
for image/video selection.
这是我的示例代码
func apiCallWithMultipart(arrMedia:[TLPHAsset], completionHandler: @escaping (DataResponse<Any>) -> Void) {
if VVSingleton.sharedInstance.isReachable {
// Show HUD
VVSingleton.sharedInstance.showHUDWithText(strText: "Please wait...")
// VVSingleton.sharedInstance.showHUDWithText(strText: "Loading \(url.absoluteString.split(separator: "/").last ?? "")")
headers = createHeadersMultipart()
DispatchQueue.main.async {
AF.upload(multipartFormData: { (multipartFormData) in
// Add parameters
for (key, value) in self.parameters {
let paramValue = "\(value)" as String
multipartFormData.append(paramValue.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key as String)
}
for media in arrMedia {
if media.type == TLPHAsset.AssetType.video {
media.phAsset?.requestContentEditingInput(with: PHContentEditingInputRequestOptions(), completionHandler: { (phContentEditingInput, [AnyHashable : Any]) in
if let videoURL = (phContentEditingInput!.audiovisualAsset as? AVURLAsset)?.url {
if videoURL.isFileURL {
// do {
// let videoData = try Data(contentsOf: videoURL, options: .mappedIfSafe)
// print(videoData)
// // here you can see data bytes of selected video, this data object is upload to server by multipartFormData upload
// multipartFormData.append(videoData, withName: "album_files[]", fileName: media.originalFileName, mimeType: media.MIMEType(videoURL))
// } catch {
// print("error while create data = \(error)")
// }
//print("\(videoURL)" + media.originalFileName!)
multipartFormData.append(videoURL, withName: "album_files[]", fileName: media.originalFileName ?? "Sample", mimeType: media.MIMEType(videoURL)!)
//multipartFormData.append(videoURL, withName: "unicorn")
}
}
})
}
else if media.type == TLPHAsset.AssetType.photo {
let imageData = media.fullResolutionImage?.jpegData(compressionQuality: 1)
if let data = imageData {
multipartFormData.append(data, withName: "album_files[]", fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: MimeType_jpg)
}
}
}
}, usingThreshold: UInt64.init(), fileManager: FileManager.default, to: self.url, method: HTTPMethod.post, headers: self.headers)
.uploadProgress { progress in // main queue by default
print("Upload Progress: \(progress.fractionCompleted)")
print("Upload Estimated Time Remaining: \(String(describing: progress.estimatedTimeRemaining))")
print("Upload Total Unit count: \(progress.totalUnitCount)")
print("Upload Completed Unit Count: \(progress.completedUnitCount)")
}
.responseJSON { (response) in
// Error Handle : https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling
// #file String The name of the file in which it appears.
// #line Int The line number on which it appears.
// #column Int The column number in which it begins.
// #function String The name of the declaration in which it appears.
// #dsohandle String The dso handle.
print("\n\n\nFile -> \(#file), Function -> \(#function), Line -> \(#line)\n")
print("Request: \(String(describing: response.request))") // original url request
print("Parameters: \(self.parameters.description)") // original url request
//print("Response: \(String(describing: response.response))") // http url response
//print("Result: \(response.result)") // response serialization result
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("String Data: \(utf8Text)") // original server data as UTF8 string
}
if let json = response.value {
print("JSON Response : \(json)") // serialized json response
}
// Hide HUD
// DispatchQueue.main.asyncAfter(deadline: .now()) {
// your code here
if Thread.isMainThread {
VVSingleton.sharedInstance.hideHUD()
}
else {
DispatchQueue.main.async {
VVSingleton.sharedInstance.hideHUD()
}
}
completionHandler(response)
}
}
} else {
// Show Network error
VVSingleton.sharedInstance.showAlertMessage(TitleString: "Network Error", AlertMessage: "Your device is not connected to the Internet", viewController: delegate)
}
}
上传进度日志
Upload Progress: 1.0
Upload Estimated Time Remaining: nil
Upload Total Unit count: 885
Upload Completed Unit Count: 885
最佳答案
您应该为您的视频添加 Data
类型,当使用 Alamofire 发送多部分请求时,请尝试如下操作:
do {
let videoData = try Data(contentsOf: videoURL)
multipartFormData.append(videoData, withName: "album_file", fileName: "album_file", mimeType: "mp4")
} catch {
debugPrint("Couldn't get Data from URL: \(videoUrl): \(error)")
}
关于ios - 使用 alamofire 5 Swift 5 将视频上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785274/
我是一名优秀的程序员,十分优秀!