[Answer]-File upload from swift to django

1👍

Your view should be able to receive FILES with the POST request and the regular thing to do when you receive an uploaded picture from regular html form. then all you have to do is to create multipart form in iOS and post it to the receiver url. Once you submit the photo in the form, you django application should do the S3 thing. So simply your question is how to post a selected image from iOS to a web-service form as a multipart form. This code demonstrate that.

var imageData :NSData = UIImageJPEGRepresentation(imagenReduced, 1.0);       
var request: NSMutableURLRequest?
let HTTPMethod: String = "POST"
var timeoutInterval: NSTimeInterval = 60
var HTTPShouldHandleCookies: Bool = false

request = NSMutableURLRequest(URL: url)
request!.HTTPMethod = HTTPMethod
request!.timeoutInterval = timeoutInterval
request!.HTTPShouldHandleCookies = HTTPShouldHandleCookies


let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
request!.setValue(contentType, forHTTPHeaderField:"Content-Type")
var body = NSMutableData();


 let tempData = NSMutableData()
 let fileName = filenames + ".jpg" //"prueba.jpg"
 let parameterName = "userfile"


let mimeType = "application/octet-stream"

tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
let fileNameContentDisposition = fileName != nil ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData(imageData)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

body.appendData(tempData)

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

request!.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request!.HTTPBody = body



var vl_error :NSErrorPointer = nil
var responseData  = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil, error:vl_error)

var results = NSString(data:responseData, encoding:NSUTF8StringEncoding)
println("finish \(results)")
👤Othman

Leave a comment