使用Swift 3将参数和数据发送到Web服务器 [英] Send parameters AND data to web server with Swift 3

查看:103
本文介绍了使用Swift 3将参数和数据发送到Web服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图弄清楚如何将照片从iPhone发送到我的网络服务器。

I'm trying to figure out how to send a photo from an iPhone to my web server.

我还需要发送包含照片大小的参数,它是与参数数据在同一请求中的照片的文件名和其他附加信息。

I also need to send parameters containing the size of the photo, it's filename and other additional information about the photo in the same request as the parameter data.

我认为以下代码在正确的轨道上,但我在哪里放参数数据名为 params

The code below is on the right track I think, but where do I put the parameter data called params:

        let params: Array<String> = [aI.filename, String(aI.size), String(aI.dateTime.year), String(aI.dateTime.month), String(aI.dateTime.day), String(aI.dateTime.hour), String(aI.dateTime.minute), String(aI.dateTime.second), String(aI.dateTime.millisecond)]


        var serverURL = URL(string: "http://192.168.0.23/upload.php");
        var req = NSMutableURLRequest(url: serverURL!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 60.0);
        //Set request to post
        req.httpMethod = "POST";

        //Set content type
        req.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type");


        let task = URLSession.sharedSession().dataTaskWithRequest(req){ data, response, error in
            if error != nil{
                print("Error -> \(error)")
                return
            }

            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                print("Result -> \(result)")

            } catch {
                print("Error -> \(error)")
            }
        }

        task.resume()
        return task


推荐答案

虽然有些答案让我朝着正确的方向前进,但他们仍然不适合我的项目,所以我继续谷歌搜索我设法在下面的文章中找到了我需要的内容: http://swiftdeveloperblog.com/image- upload-example /

Allthough some of the answers pushed me in the right direction, they still didn't fit my project and so I continued googling an I managed to find exactly what I needed in the following article: http://swiftdeveloperblog.com/image-upload-example/

我需要异步发出HTTP请求并使用会话,
我没有在问题中指定,因为问题只是关于如何在一个请求中发送几个参数和数据。

I needed to make the HTTP request asynchronously and using sessions, which I didn't specify in the question because the question was merely about how to send both several parameters along with data in one single request.

它被称为多部分表格数据这样做。

我不得不修改文章中的代码以使其适用于我的应用程序,
所以我正在分享我的 Swift 3 代码如下:

I had to modify the code from the article a little bit to make it work for my application, so I'm sharing my Swift 3 code below:

触发代码

let params = [
            "filename"      : chunkOwner.filename                       ,
            "size"          : String(describing: chunkOwner.size)                   ,
            "year"          : String(chunkOwner.dateTime.year)          ,
            "month"         : String(chunkOwner.dateTime.month)         ,
            "day"           : String(chunkOwner.dateTime.day)           ,
            "hour"          : String(chunkOwner.dateTime.hour)          ,
            "minute"        : String(chunkOwner.dateTime.minute)        ,
            "second"        : String(chunkOwner.dateTime.second)        ,
            "millisecond"   : String(chunkOwner.dateTime.millisecond)   ,
        ]

uploadChunk(url: URL(string: "http://192.168.0.23/upload.php")!, data: photoData, params: params)

上传代码:

func uploadData(url: URL, data: Data!, params: [String: String])
    {
        let cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData;
        let request = NSMutableURLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: 6.0);
        request.httpMethod = "POST";

        let boundary = generateBoundaryString()

        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")


        if(data == nil)  { return; }

        request.httpBody = createBodyWithParameters(parameters: params, filePathKey: "file", data: data, boundary: boundary)



        //myActivityIndicator.startAnimating();

        let task = URLSession.shared.dataTask(with: request as URLRequest) {
            data, response, error in

            if error != nil {
                print("error=\(error)")
                return
            }

            // You can print out response object
            print("******* response = \(response)")

            // Print out reponse body
            let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("****** response data = \(responseString!)")

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary

                print(json)



            }catch
            {
                //if you recieve an error saying that the data could not be uploaded,
                //make sure that the upload size is set to something higher than the size
                print(error)
            }


        }

        task.resume()

    }


    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, data: Data!, boundary: String) -> Data {
        var body = Data();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString(string: "--\(boundary)\r\n")
                body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString(string: "\(value)\r\n")
            }
        }

        let mimetype = "text/csv"

        body.appendString(string: "--\(boundary)\r\n")
        body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(parameters!["filename"]!)\"\r\n")
        body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")


        body.append(data)
        body.appendString(string: "\r\n")

        body.appendString(string: "--\(boundary)--\r\n")

        return body
    }




    func generateBoundaryString() -> String {
        return "Boundary-\(NSUUID().uuidString)"
    }

还在您班级以外的 .swift 文件底部包含以下代码:

Also include the following code at the bottom of your .swift file outside of your class:

extension Data {
    mutating func appendString(string: String) {
        append(string.data(using: .utf8)!)
    }
}

对于PHP上传脚本,我做了一些更改,现在看起来像这样:

And for the PHP upload script I did some changes and now looks like this:

<?php
    $target_dir = "/var/www/html/uploads";if(!file_exists($target_dir)){
        mkdir($target_dir, 0777, true);
    }

    $target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
    echo count("size: ".$_FILES["file"]["tmp_name"]);


    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)){

        echo json_encode([
            "Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
            "Status" => "OK",
        ]);

    } else {

        echo json_encode([
            "Message" => "Sorry, there was an error uploading your file.",
            "Status" => "Error",
        ]);

    }
?>

重要提示:


如果您的服务器php文件名为
php.ini 配置为接受较小的文件,您的应用将无法上传数据比你试图上传的
数据。

Your app will fail to upload data if your server php file called php.ini is configured to accept files smaller than the data you're trying to upload.

例如:如果 php.ini 是配置为接受2 MB,然后将忽略大于2 MB的任何
上传,并且您的应用将收到
回复,说明出现了问题。

For example: If php.ini is configured to accept 2 MB, then any uploads larger than 2 MB will be ignored and your app will receive a response saying that something went wrong.

要更改 php.ini 中的文件大小接受,您需要查找
变量名为 upload_max_filesize post_max_size 并将其更改为系统所需的任何文件大小

To change the file size acceptance in php.ini you need to look for the variable called upload_max_filesize and post_max_sizeand change those to whatever file size your system requires.

这篇关于使用Swift 3将参数和数据发送到Web服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆