将文本文件上传到HTTP服务器swift

时间:2016-07-12 03:45:35

标签: swift file-upload httpserver

我创建了一个尝试使用swift将文本文件上传到HTTP Server的应用程序。我的代码如下:

do {
        let post:NSString = "command=upload&file=file.eg"
        let postCommand:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
        NSLog("PostData: %@",post);

        let url:NSURL = NSURL(string:"https://www.example.com/example-2.php")!
        let file = "file.eg" 
        if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
            let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)

            let postData:NSData = NSData(contentsOfURL: path)!

            let myRequestData:NSMutableData = NSMutableData()
            myRequestData.appendData(postCommand)
            myRequestData.appendData(postData)

            let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"
            request.HTTPBody = myRequestData

            let session: NSURLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue())
            let task: NSURLSessionUploadTask = session.uploadTaskWithRequest(request, fromData: postData)

            task.resume()

            var reponseError: NSError?
            var response: NSURLResponse?

            var urlData: NSData?
            do {
                urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
            } catch let error as NSError {
                reponseError = error
                urlData = nil
            }

            if ( urlData != nil ) {
                let res = response as! NSHTTPURLResponse!;

                NSLog("Response code: %ld", res.statusCode);

                if (res.statusCode >= 200 && res.statusCode < 300){
                    let responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

                    NSLog("Response ==> %@", responseData);

                    let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary

                    let success:NSInteger = jsonData.valueForKey("success") as! NSInteger

                    NSLog("Success: %ld", success)

                    if(success == 1)
                    {
                        NSLog("Upload SUCCESS");


                    } else {
                        var error_msg:NSString

                        if jsonData["error_message"] as? NSString != nil {
                            error_msg = jsonData["error_message"] as! NSString
                        } else {
                            error_msg = NSLocalizedString("INCORRECT_EMAIL_OR_PASSWORD", comment: "Incorrect email or password!")
                        }

                    }
                }
            }
        }
     } catch {
     //fail to upload
     }

代码无效。我错过了什么吗?我做了一些研究并找到了这段代码

            let content:String = "multipart/form-data; boundary=ASDsdfgrtRT"
            request.setValue(content, forHTTPHeaderField: "Content-Type")
            request.setValue("\(myRequestData.length)", forHTTPHeaderField: "Content-Length")

想问一下代码“request.setvalue”是什么?

0 个答案:

没有答案