我创建了一个应用程序,允许用户将图像和几个上传到我们的服务器。如果我只发布文本数据,我的代码会成功将数据发布到服务器,但是当我尝试使用图像数据发布文本数据时,我的服务器会抛出异常。
这是我的代码:
class func Enroll(image: UIImage, date: String, studentid: String, guardianid:String, type:String){
//date,student_id,type,guardian_id,image, type
var textBody : String?
let imageData = UIImagePNGRepresentation(image)
let boundary = NSString(format: "---------------------------14737809831466499882746641449")
let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
let URL: NSURL = NSURL(string: "http://api-cc.appsence.net/v1/signs")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
let body : NSMutableData = NSMutableData()
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_img\"; filename=\"img.jpg\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData!)
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
//fill text value here
textBody = "date=\(date)&student_id=\(studentid)&guardian_id=\(guardianid)&type=\(type)"
print("text body : \(textBody!)")
let bodyTextData = textBody!.dataUsingEncoding(NSUTF8StringEncoding);
body.appendData(bodyTextData!)
request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
// if data string use data using encoding
request.HTTPBody = body
NSURLSession.sharedSession().dataTaskWithRequest(request){ (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if error == nil{
print("sukses : \(NSString(data: data!, encoding: NSUTF8StringEncoding)!)")
}else{
print("ini error save \(NSString(data: data!, encoding: NSUTF8StringEncoding)!)")
}
}.resume()
}
如何解决此问题?
答案 0 :(得分:0)
Alamofire 3 +
// import Alamofire
func uploadWithAlamofire() {
let image = UIImage(named: "myPhoto")!
// define parameters
let parameters = [
"hometown": "bodrum",
"living": "izmir"
]
// Begin upload
Alamofire.upload(.POST, "upload_url",
// define your headers here
headers: ["Authorization": "auth_token"],
multipartFormData: { multipartFormData in
// import image to request
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "myImage.png", mimeType: "image/png")
}
// import parameters
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
}, encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold,
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { result in
debugPrint(result)
}
case .Failure(let encodeError):
print(encodeError)
}
})
}
答案 1 :(得分:0)
在我的一个应用程序中,我在下面的方法中将图像发布到server.Below是客观的C语法。但是你可以在swift中使用相同的方法
1)将图像转换为base 64字符串 NSData * imageData = UIImageJPEGRepresentation(< #UIImage * _Nonnull image#>,< #CGFloat compressionQuality#>); NSString * base64String = [imageData base64EncodedStringWithOptions:0];
2)创建一个字典并将base 64字符串添加到字典
NSMutableDictionary * imagedict = [[NSMutableDictionary alloc] init];
[imagedict setObject:base64String forKey:@"image"];
3)转换为json并使用nsurl会话将其发布到您的服务器
NSData * incidentData = [NSJSONSerialization dataWithJSONObject:imagedict options:0 error:& err];
4)您的服务器将以json的形式接收请求并解析它以获取图像并将基本64字符串转换回图像