使用Swift的NSURLSession将图像上传到烧瓶服务器

时间:2016-05-19 20:30:58

标签: python ios swift image flask

所以我无法让Flask接收我从iOS代码发送的图像(在烧瓶上不断出现400错误)。我不完全确定问题来自iOS方面或烧瓶方面,但我怀疑这可能是因为图像在iOS端没有正确编码。

Swift代码:

func uploadImage(image: UIImage) -> Void{
    //Convert the image to a data blob
    guard let png = UIImagePNGRepresentation(image) else{
        print("error")
        return
    }

    //Set up a network request
    let request = NSMutableURLRequest()
    request.HTTPMethod = "POST"
    request.URL = NSURL(string: "http://127.0.0.1:5000/")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("\(png.length)", forHTTPHeaderField: "Content-Length")
    request.HTTPBody = png
    // Figure out what the request is making and the encoding type...

    //Execute the network request
    let upload = NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: png) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        //What you want to do when the upload succeeds or fails
    }

    upload.resume()

}

Flask代码:

@app.route('/')
def projects():
    if request.method == "POST":
    file = request.files['file']
    if file:
         img = Image.open(file)
         img.show()
return render_template("home.html")

谢谢!

1 个答案:

答案 0 :(得分:-1)

以下代码

file = request.files['file']
Flask中的

意味着您希望从multipart/form-data POST请求中获取文件。

尝试以能够执行multipart/form-data次请求的方式重写代码,并且不要忘记在boundary标题中指定content-type

以下是示例代码:

    let boundary = "Boundary-\(NSUUID().UUIDString)"

    let url = NSURL(string: "https://example.com/target.py")!
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    let path1 = NSBundle.mainBundle().pathForResource("image_x", ofType: "png") as String!
    request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", paths: [path1], boundary: boundary)