在Swift中发布到服务器的图像(或视频) [英] Image(or video) posting to server in Swift

查看:144
本文介绍了在Swift中发布到服务器的图像(或视频)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我在swift中使用NSURLSession将json数据发布到服务器,如下所示

Hi I am posting json data to server using NSURLSession in swift as below

         var request = NSMutableURLRequest(URL: NSURL(string: "http://mypath.com"))
         var session = NSURLSession.sharedSession()
         request.HTTPMethod = "POST"

         var params2 :NSDictionary = ["email":"myemail@gmail.com"]
         var params :NSDictionary = ["function":"forgotPassword", "parameters":params2]

         var err: NSError?
         request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in




            var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
            let decodedJson = NSJSONSerialization.JSONObjectWithData(data, options: nil, error:nil) as NSDictionary

             println("Body: \(strData)")

            //Here I am getting response

            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

            // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
            if(err != nil) {
                println(err!.localizedDescription)
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: '\(jsonStr)'")
            }
            else {
                // The JSONObjectWithData constructor didn't return an error. But, we should still
                // check and make sure that json has a value using optional binding.
                if let parseJSON = json {
                    // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                    var success = parseJSON["success"] as? Int
                    println("Succes: \(success)")
                }
                else {
                    // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                    let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                    println("Error could not parse JSON: \(jsonStr)")
                 }
                }
            })

            task.resume()

现在我想要多部分数据表单到服务器(图像数据/视频数据)的键值image
以及其他参数,如user_id = 15,about_video_thumb =myImagejpg

Now I want to multipart data form to server (Image data / Video data) for key value "image" along with other parameters like user_id = 15, about_video_thumb = "myImagejpg"

在客观CI中,我上传了如下图像

In objective C I am uplaoding an image like below

  -(void)upLoadThumb{


   NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
   [request setURL:[NSURL URLWithString:@"http://mypath.com/uplaodpic"]];
   [request setHTTPMethod:@"POST"];


   //Setting content type - multipart/form-data
   NSString *boundary = @"---------------------------14737809831466499882746641449";
   NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
   [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
   NSMutableData *postbody = [NSMutableData data];
  [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];





   // This is one field user_id

      [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"user_id\"\r\n\r\n%@", @"15"] dataUsingEncoding:NSUTF8StringEncoding]];
      [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];



       [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"about_video_thumb\"; filename=\"%@\"\r\n", @"myImage.jpg"] dataUsingEncoding:NSUTF8StringEncoding]];

     //Appending NSDATA

      [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
     [postbody appendData:[NSData dataWithData:appDelegate.userVdoImageData]];
     [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];


     [request setHTTPBody:postbody];
    conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
       webData = [NSMutableData data];
         }
     }

如何在swift中使用NSURLSession或NSURLConnection执行此操作?
提前致谢

How Can I do this with NSURLSession or NSURLConnection in swift ? Thanks in advance

推荐答案

如果你想在json体中上传图像,你需要对其进行编码。假设您有 UIImage 实例图像

If you want to upload image in json body you need to encode it. Suppose you have a UIImage instance image

let data = UIImageJPEGRepresentation(image, 0.5)
let encodedImage = data.base64EncodedStringWithOptions(.allZeros)

现在它被编码为base64字符串。我们可以在json体中使用它。

Now it is encoded as base64 string. We can use it in json body.

let parameters = ["image": encodedImage, "otherParam": "otherValue"]

let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "YOUR_URL")!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"

var error: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: .allZeros, error: &error)

if let error = error {
    println("\(error.localizedDescription)")
}

let dataTask = session.dataTaskWithRequest(request) { data, response, error in
    // Handle response
}

dataTask.resume()

这篇关于在Swift中发布到服务器的图像(或视频)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆