我已将视频文件上传到服务器,但文件大小为零。
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/