将照片从 swift 上传到 django api

Upload photo from swift to django api

我想从 iDevice 上传图像到网络服务器。我使用 Django API 。 照片没有上传,请问我的代码哪里错了

感谢您的帮助

var data :NSData = UIImageJPEGRepresentation( image!, 100.0)
let boundary = "Boundary-\(NSUUID.alloc().UUIDString)"
    var session = NSURLSession.sharedSession()
    let url = NSURL(string: APIURLs.uploadWorkerImage.stringByAppendingString(workerId))
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "PATCH"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    let body = NSMutableData()


    let filename = "fileName.jpeg"
    let mimetype = "image/jpeg"

    body.appendData(NSString(string: "--\(boundary)\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(string: "Content-Disposition: form-data; name=\"photo\"; filename=\"\(filename)\"\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(NSString(string: "Content-Type: \(mimetype)\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(data)
    body.appendData(NSString(string: "\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)

    body.appendData(NSString(string: "--\(boundary)\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)

    request.HTTPBody = body

    let downloadTask = session?.downloadTaskWithRequest(request)
    downloadTask?.resume()

编辑

如果我使用这个命令照片上传成功

curl -H  -X PATCH --form "photo=@static/images/close.png" http://apiurl

您使用的类型有误。 NSURLSessionDownloadTask是下载东西。您需要使用 NSURLSessionUploadTask.

问题出在图像数据中

var data :NSData =   NSData(contentsOfFile: path)!

而不是

var data :NSData = UIImageJPEGRepresentation( image!, 100.0)

希望对大家有所帮助