由于我是iOS的新用户,所以在这里呆了一段时间,我需要将图像上传到服务器,并且键和值分别为(“ file”:image),在邮递员中找到该图像。
我在How to upload images to a server in iOS with Swift?,Upload image to server - Swift 3
处尝试了几乎所有建议在这里,我尝试了一些操作,但是由于未在请求中传递密钥,因此没有得到输出响应
let url = URL(string: uploadurl);
let request = NSMutableURLRequest(url: url!);
request.httpMethod = "POST"
let boundary = "Boundary-\(NSUUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image, 1)
if (imageData == nil) {
print("UIImageJPEGRepresentation return nil")
return
}
let body = NSMutableData()
//here I need to pass the data as ["file":image]
body.append(imageData!)
request.httpBody = body as Data
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if let data = data {
// do
let json = try!JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
print("json value \(json)")
} else if let error = error {
print(error.localizedDescription)
}
})
task.resume()
请建议我如何将这些图像作为[“ file”:image]传递到体内。
预先感谢
答案 0 :(得分:0)
您可以使用URLSession
上传一个multipart/form-data
上传图片的功能
// build request URL
guard let requestURL = URL(string: "YOURURL") else {
return
}
// prepare request
var request = URLRequest(url: requestURL)
request.allHTTPHeaderFields = header
request.httpMethod = MethodHttp.post.rawValue
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// built data from img
if let imageData = image.jpegData(compressionQuality: 1) {
request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)
}
let task = URLSession.shared.dataTask(with: request,
completionHandler: { (data, _, error) -> Void in
if let data = data {
debugPrint("image uploaded successfully \(data)")
} else if let error = error {
debugPrint(error.localizedDescription)
}
})
task.resume()
将创建请求正文的函数
func createBodyWithParameters(parameters: [String: String],
filePathKey: String,
imageDataKey: Data,
boundary: String) -> Data {
let body = NSMutableData()
let mimetype = "image/*"
body.append("--\(boundary)\r\n".data(using: .utf8) ?? Data())
body.append("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filePathKey)\"\r\n".data(using: .utf8) ?? Data())
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: .utf8) ?? Data())
body.append(imageDataKey)
body.append("\r\n".data(using: .utf8) ?? Data())
body.append("--\(boundary)--\r\n".data(using: .utf8) ?? Data())
return body as Data
}
private func generateBoundaryString() -> String {
return "Boundary-\(Int.random(in: 1000 ... 9999))"
}
}
数据扩展
extension NSMutableData {
func appendString(_ string: String) {
if let data = string.data(using: String.Encoding.utf8,
allowLossyConversion: true) {
append(data)
}
}
}
答案 1 :(得分:0)
尝试一下。将文件保存在documentDirectory
中。使用boundary
将文件添加到正文中,该文件是随机字符串。然后将文件的密钥添加为name=\"file\"
if !fileName.isEmpty {
let pathComponents = [NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!, fileName]
outputFileURL = NSURL.fileURL(withPathComponents: pathComponents) //get the image file from documentDirectory
//add file to body (name=\"file\")
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpeg\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: image/*\r\n\r\n".data(using: String.Encoding.utf8)!)
do {
try body.append(Data(contentsOf: outputFileURL!))
} catch {
print(error)
}
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
}