首先-我知道安全隐患,并且我不应该以这种方式这样做。 我正在尝试从IOS应用发送图像并创建图像到FTP服务器。 FTP服务器输入用户名和密码。我不确定自己在做什么错。
错误: 任务。<4> HTTP加载失败,65805/387字节(错误代码:-1005 [4:-4]) 网络连接丢失。
func PostImage(){
let userName = "Username"
let password = "password"
let loginString = String("\(userName):\(password)")
let loginData = loginString.data(using: .utf8)
let base64LoginString = loginData.base64EncodedString()
let imagetest = UIImage(named: "ImageTest")
guard let url = URL(string: "ftp://IPAddress:Port/testfolder") else { return }
print(url)
var request = URLRequest(url: url)
request.httpMethod = "POST"
let boundary = generateBoundary()
let data = createData(image: imagetest!, boundary: boundary)
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
**request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")**
let session = URLSession.shared
session.uploadTask(with: request, from: data) {
(data, response, error) in
if let httpresponse = response as? HTTPURLResponse {
print(httpresponse.statusCode)
}
if error != nil {
print(error!.localizedDescription)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
func createData(image: UIImage, boundary: String)-> Data{
let lineBreak = "\r\n"
var data = Data()
let key = "image"
let fileName = "test"
let imagedata = image.pngData()
let mimeType = "image/png"
data.append("--\(boundary + lineBreak)")
data.append("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(fileName)\"\(lineBreak)")
data.append("Content-Type: \(mimeType + lineBreak + lineBreak)")
data.append(imagedata!)
data.append(lineBreak)
data.append("--\(boundary)--\(lineBreak)")
return data
}
func generateBoundary() -> String {
return "Boundary-\(NSUUID().uuidString)
}