我正在尝试使用swift中的POST方法上传图像。我在这里给出了我的全部代码。
ViewController类:
$scope.dtOptions = DTOptionsBuilder
.fromFnPromise(function() {
var deferred = $q.defer();
deferred.resolve(users);
return deferred.promise;
})
.withBootstrap() // Style with Bootstrap
...
};
我正在这样做......
import UIKit
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
@IBOutlet var myImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func selectPhotoButtonTapped(sender: AnyObject) {
let myPickerController = UIImagePickerController()
myPickerController.delegate = self
myPickerController.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
func myImageUploadRequest(){
let myurl = NSURL(string: "http://52.32.31.149/devweatherscope/public/user/register")
let request = NSMutableURLRequest(URL: myurl!)
request.HTTPMethod = "POST"
let parameter:[String:String] = ["register_type":"normal", "email" :"mavin5623@gmail.com","password":"password","full_name":"mavin","device_type":"ios"]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
//let img:UIImage = UIImage(named: "b1.jpg")!
let imageData = UIImageJPEGRepresentation((myImageView.image!),1)
if (imageData == nil ){ return; }
request.HTTPBody = createBodyWithParameters(parameter,filePathkey: "profile_pic",imageDataKey:imageData! ,boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
print("***response=\(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("****responsedata=\(responseString!)")
dispatch_async(dispatch_get_main_queue(),{
self.myImageView.image = nil
})
}
task.resume()
}
func createBodyWithParameters(parameter:[String: String]?, filePathkey:String, imageDataKey: NSData,boundary:String)-> NSData {
let body = NSMutableData();
if parameter != nil{
for (key,value) in parameter!{
body.appendString("\(boundary)")
body.appendString("content-Disposition:form-data;name=\"\(key)\r\r\n")
body.appendString("\(value)\r\n")}
}
let filename = "b1.jpg"
let mimetype = "image/jpg"
body.appendString("---\(boundary)\r\n")
body.appendString("content-Disposition: form-data ; name=\(filePathkey);filename=\(filename)\r\n")
body.appendString("content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
@IBAction func uploadButtonTapped(sender: AnyObject) {
myImageUploadRequest()
}
}
extension NSMutableData{
func appendString(string: String){
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
}
我已输入所有参数
***response=Optional(<NSHTTPURLResponse: 0x7fc87503bd50> { URL: http://52.32.31.149/devweatherscope/public/user/register } { status code: 400, headers {
"Cache-Control" = "no-cache";
Connection = close;
"Content-Length" = 58;
"Content-Type" = "application/json";
Date = "Wed, 27 Apr 2016 06:32:11 GMT";
Server = "Apache/2.4.7 (Ubuntu)";
"Set-Cookie" = "laravel_session=eyJpdiI6Ild5KzM4NTdCRnM3aGM2SmpSSWlFckE9PSIsInZhbHVlIjoicFUzNUFGRUVUYkc5UlpINW0xM1lDK21YcFZLZTIrZlhIWWp4eG9Tbjc0bmhxUWZlaWJtXC9nZVZYVjRuUTBaN0xIWE52MkxvczBKUTM5aE5vdXd2bzB3PT0iLCJtYWMiOiJhZTllZDMyNTU5OGRmOTMyMzgxNTIyNjNjYjdhMDFlZjQzNGI3YzdhZDcyOWE0N2IxNGU5MzliMjMzYTc2N2ZkIn0%3D; expires=Wed, 27-Apr-2016 08:32:30 GMT; Max-Age=7200; path=/; httponly";
} })
****responsedata={"status":false,"reason":"register type field is missing"}
但是响应显示缺少寄存器类型。如何解决此问题并且我想成功上传我的图像?