将视频文件上传到服务器

时间:2016-03-01 13:20:54

标签: 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

1 个答案:

答案 0 :(得分:0)

埃里克 您不应该使用NSMutableURLRequest,您应该使用NSURLSession。这是我发布的其他代码

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

我回复的这篇文章也显示了它的实现。 NSMutableURLRequest正在折旧。

这是关于这个主题的几个优秀教程中的一个;不,我不是伪装的Bart Jakobs:)

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