我在名为jetty的服务器上传文件时遇到问题。
我有用于多部分文件上传的代码
func post(url: String,ticketId: String, workLogDecs: String, status: String,img: UIImage){
var request = NSMutableURLRequest(URL: NSURL(string: "\(baseURL)\(url)")!)
let imageData = UIImageJPEGRepresentation(img, 1)
let parameters = ["workLogDesc":"\(workLogDecs)","requestId":"\(ticketId)","status":"\(status)"]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.HTTPBody = createBodyWithParameters(parameters, filePathKey: "files", imageDataKey: imageData, boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
println("error=\(error)")
var userInfo = error.userInfo
var errorString = userInfo?.description
println("errorString \(errorString)")
return
}
// You can print out response object
println("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("****** response data = \(responseString!)")
}
task.resume()
}
这是我用params创建body的代码:
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
var body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("–\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "test.jpg"
let mimetype = "image/jpg"
body.appendString("–\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("–\(boundary)–\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
我使用扩展名:
extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
我的问题是我收到错误并说“无法解析响应”
这是我的错误日志:
Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response" UserInfo=0x7ff43a74c850 {NSUnderlyingError=0x7ff43a6b4660 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1017.)", NSErrorFailingURLStringKey=http://192.168.137.160:8082/ws/worklog/new, NSErrorFailingURLKey=http://192.168.137.160:8082/ws/worklog/new, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-1, NSLocalizedDescription=cannot parse response}
我的代码有问题。我是这个多部分文件上传的新手。如果还有其他方法可以帮助我。感谢。
答案 0 :(得分:3)
看起来您的代码可能来自this answer,但引入了一些问题:
如果您使用单个短划线,则需要两个破折号,例如:
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
和
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
注意,对你的破折号要非常非常小心。问题代码示例中的破折号似乎是连字符,而不仅仅是连字符。 (有些文字处理器会用一个短划线代替两个连字符......它也解释了第1点,那个额外的连字符消失了。)
此外,您似乎没有设置请求的HTTPMethod
:
request.HTTPMethod = "POST"
最后一点是您问题中错误的实际来源。但是你还必须修复连字符,否则请求仍然会失败。