ios - 上传视频文件到服务器

标签 ios swift upload

我已将视频文件上传到服务器,但文件大小为零。

let url:NSURL? = NSURL(string: (Config.sampleuploadurl as String)+"/uploadServlet?chehara_email=\(candit_email)")
// let url:NSURL? = NSURL(string: (Config.apiUrl as String)+"/UploadServlet?chehara_email=\(candit_email)")
print(url)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"
let boundaryConstant = "Boundary-7MA4YWxkTLLu0UIW"; // This should be auto-generated.
let contentType = "multipart/form-data; boundary=" + boundaryConstant

let fileName:String = videoName

let mimeType = "text/MOV"
let fieldName = "uploadFile"

request.setValue(contentType, forHTTPHeaderField: "Content-Type")

var error: NSError?
var dataString = "--\(boundaryConstant)\r\n"

dataString += "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(fileName)\"\r\n"
print("dataString")

dataString += "Content-Type: \(mimeType)\r\n\r\n"
print(dataString)

dataString += String(contentsOfFile: videoName, encoding: NSUTF8StringEncoding, error: &error)!   // This is Error Line

dataString += "\r\n"
dataString += "--\(boundaryConstant)--\r\n"

let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
print("Request")
print(requestBodyData)

request.HTTPBody = requestBodyData
print(request.HTTPBody)

})

我引用这个tutorial .

最佳答案

埃里克, 你不应该使用 NSMutableURLRequest,你应该使用 NSURLSession。这是我在其他地方发布的一些代码

http://stackoverflow.com/questions/35604866/swift-send-file-to-server/35609325#35609325

我回复的这篇文章也显示了它的实现。 NSMutableURLRequest 正在被贬值。

这是关于该主题的几个优秀教程之一;不,我不是伪装的巴特·雅各布斯:)

http://code.tutsplus.com/tutorials/networking-with-nsurlsession-part-1--mobile-21394

关于ios - 上传视频文件到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35724090/

相关文章:

使用 Powershell 与 FileZilla 进行 Ftp 上传

ios - 从 SceneKit 中的 SCNNode 中提取几何信息

iphone - 设备中未播放警告声音?

ios - 我们如何知道相册中是否已存在图像?

ios - 如何在 editActionsForRowAt 操作中调整图标

c++ - POCO : How to upload image to webser using poco in c++

ios - NSMutableArray 中的addObject 是复制还是保留?

ios - 如何创建像 Vine App 一样的下拉表格 View

objective-c - 如何在 Swift 中编码 NSFetchedResultsController

image - Drupal 中上传的图像被自动删除