表单的提交

// 原生表单的提交
    func creatFormRequest(imgData:Data) {
        
        let url = "http://www.baidu.com"
        let NL = "\r\n"
        
        let boundary  = "ABC" // 自定义分界符
        let segmentBoundary = "--" + boundary
        let endBoundary = "--" + boundary + "--"
        
        /*
         bodyHeaderStr:
         分界符
         内容
         */
        var bodyHeaderStr:String = "\(segmentBoundary)\(NL)"
        bodyHeaderStr = bodyHeaderStr + "Content-Disposition: form-data;name=\"objectName\"\(NL)\(NL)"// content-Disposition的值不加引号,但是其他的值要加引号
        
        // 内容
        bodyHeaderStr = bodyHeaderStr + "1.png/01X3\(NL)"
        bodyHeaderStr = bodyHeaderStr + "Content-Disposition: form-data;filename=\"1.png\";fileid=\"01X3\"\(NL)"
        bodyHeaderStr = bodyHeaderStr + "Content-Type:image/png\r\n\r\n";
        
        /*
         bodyData:
         bodyHeaderStr.data
         img.data
         endBoundaryStr.data
         */
        let mData = NSMutableData()
        mData.append(bodyHeaderStr.data(using: .utf8)!)
        mData.append(imgData)
        mData.append((NL + endBoundary).data(using: .utf8)!)
        
        /*
         Content-Type = multipart/form-data;boundary=ABC
         */
        var urlRequest = URLRequest.init(url: URL.init(string: url)!)
        urlRequest.allHTTPHeaderFields = ["token":"XXXX"]
        urlRequest.httpMethod = "post"
        urlRequest.setValue("Content-Type", forHTTPHeaderField: "multipart/form-data;boundary=\(boundary)")
        urlRequest.addValue("\(mData.length)", forHTTPHeaderField: "Content-Length")
        urlRequest.httpBody = mData as Data
        urlRequest.timeoutInterval = 10
        
        let session = URLSession.init(configuration: URLSessionConfiguration.default)
        let task = session.dataTask(with: urlRequest) { (data, response, error) in
            
        }
        task.resume()
    }

// Alamofire表单的提交
    func creatAlamofireFrom() {
        let url = "https://www.baidu.com"
        Session.default.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append("Luc".data(using: .utf8)!, withName: "name")
            multipartFormData.append("19".data(using: .utf8)!, withName: "age")
        }, to: url).response { (response) in
            
        }
    }

你可能感兴趣的:(表单的提交)