将图像上传到服务器详细说明初学者 [英] Uploading image to server Detail Explanation for Beginner

查看:86
本文介绍了将图像上传到服务器详细说明初学者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将图片上传到服务器,因为有很多关于通过AFNetworking和NSURLSession上传图片的问题以及其他上传所有我想问的方法是我没找到一个回答解释关于事情是如何运作的整个概念以及我在搜索youtube时发生了什么事情也在Swift中提供了所有的东西并且完全相信我没有解释和我的结果我发现这个答案看起来很熟悉我

I'm working on uploading an image to a server from last two days as there are tons of questions about uploading an image through AFNetworking and NSURLSession and other methods of uploading all I'm asking is I didn't found a single answer explaining the whole concept about how the things work and what is going on under the hood I searched youtube also all the stuff are available in Swift and trust me no Explanation at all and from my result I found this answer is something that looks familiar to me

    //Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

//Create an URLRequest
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

//Create POST Params and add it to HTTPBody
NSString *params = @"api_key=APIKEY&email=example@example.com&password=password";
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    //Handle your response here
}];

[dataTask resume];









以及关于此主题的最受欢迎的答案是用户 XJones : -

Here's code from my app to post an image to our web server:

// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]];
[_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]];
[_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]];
[_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"];

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ 
NSString* FileParamConstant = [NSString stringWithString:@"file"];

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@""]; 

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];                                    
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];









但我的观点是我正在自学,对于没有解释的初学者来说很难理解所以我所要求的只是一个解释,一个关于整个过程的细节解释,如果有人很难花这个问题,因为不管你信不信,我发现这是迄今为止最困难的话题,因为主要原因是没有关于整个过程的教程,如果有人现在可以迈出一步并解释它的概念,也没有对初学者的解释对明天学习的学生更容易。因此,任何能够详细解释这一点以及上传过程如何运作以及参考的一些步骤的人都将不胜感激。



But my point is I'm learning on my own and it is very difficult to understand for the beginner without explanation so All I'm asking is an explanation, an Detail explanation about the whole process if someone have a hard time to spend on this question because believe it or not I found this the hardest topic till now because the main reason is there are no tutorials about the whole process and also no explanation at all for beginners if someone can a step now and explain the concept it'll be easier to the students who will learn tomorrow. So anybody who can explain this in detail and how the uploading process works and some steps for the reference will be greatly appreciated.


注意:考虑我有一个API和一个密钥图像。

Note : Consider I Have an API and a Key "image" .


推荐答案

这里我们要看一下图片上传以及一些**参数因为大多数时候我们上传图像以及一些参数,例如userId。

here we gonna look at image uploading along with some **parameters because most of time we upload image along with some parameters such as userId.


  • 在深入讨论我们的话题之前我提供了执行这些工作的代码来源,所有我们将在下面看到的详细信息来自其他一些堆栈溢出线程和其他一些网站,我将提供所有链接供您参考。

  • Before going deep into our topic let me provide the code for doing the stuff source,All the details we gonna see below are from some other stack overflow threads and some from other sites,i'll provide all the links for your reference.

-(void)callApiWithParameters:(NSDictionary *)inputParameter images:(NSArray *)image  imageParamters:(NSArray *)FileParamConstant{

//1
   NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

   [request setHTTPShouldHandleCookies:NO];
   [request setTimeoutInterval:30];
   [request setHTTPMethod:@"POST"];

//2
   NSString *boundary = @"------CLABoundaryGOKUL";

//3
   NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
   [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

//4
   NSMutableData *body = [NSMutableData data];

   for (NSString *key in inputParameter) {

   [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithFormat:@"%@\r\n", [inputParameter objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];
  }

   for (int i = 0; i < image.count; i++) {

      NSData *imageDatasss = UIImagePNGRepresentation(image[i]);

      if (imageDatasss)
      {
          [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
          [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant[i]] dataUsingEncoding:NSUTF8StringEncoding]];
          [body appendData:[@"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
          [body appendData:imageDatasss];
          [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
     }
  }

  [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//5
  [request setHTTPBody:body];

//6
  [request setURL:[NSURL URLWithString:@"http://changeThisWithYourbaseURL?"]];//Eg:@"http://dev1.com/PTA_dev/webservice/webservice.php?"

//7
  [NSURLConnection sendAsynchronousRequest:request
                               queue:[NSOperationQueue mainQueue]
                   completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                       NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;

                       //8
                       if ([httpResponse statusCode] == 200) {
                           NSDictionary * APIResult =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                           NSLog(@"Response of %@: %@",[inputParameter valueForKey:@"service"],APIResult);

                       }else{
                           //9
                           NSLog(@"%@",error.localizedDescription);
                       }
                   }];


 }

注意:由于这是一个广泛的主题,我提供了详细信息的文档链接。

NOTE: Since it is a broad topic i have provided documentation link for detail info.


  1. 我们正在使用** NSMutableURLRequest **而不是** NSURLRequest **因为我们要向它附加一些数据。如果您需要对可变网址请求做一些深入的澄清,请通过此文档


    • setHTTPShouldHandleCookies 在这里我们必须决定是否要使用cookies。要了解更多关于访问

    • setTimeoutInterval 这有助于为网址请求设置时间限制。在给定时间后添加时间间隔(以秒为单位),请求将被终止。

    • setHTTPMethod 很多 methods.But在很多情况下我们使用 GET POST 方法.POST和GET之间的差异是这里在这里

  1. We are using ** NSMutableURLRequest** instead of ** NSURLRequest** because we gonna append some data to it.if you need some deep clarification about mutable url request go through this documentation.
    • setHTTPShouldHandleCookies here we have to decide whether we are going to use cookies or not.To know more about visit
    • setTimeoutInterval this helps to set a time limit to url request.Add time interval in seconds after the given time,request will be terminated.
    • setHTTPMethod there are many methods.But we use GET and POST methods in many cases.Difference between POST and GET is here and here

NSMutableData * body 我们会将所有参数和值附加到此数据中,然后将 setHTTPBody 附加到 UrlRequest 即可。

NSMutableData * body we gonna append all the parameters and values to this data and later setHTTPBody to the UrlRequest.


  • 如果我们称之为'callApiWithParameters'方法

  • If this is how we call the 'callApiWithParameters' method

 - (IBAction)Done:(id)sender{
        NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys:
                      @"1",@"user_id" ,
                      "XXX",@"name" ,
                      nil];
         NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:@"Test"],[UIImage imageNamed:@"Test1"],nil];
         NSArray * imageParameters = [NSArray arrayWithObjects:@"img_one",@"img_two",nil];
         [self callApiWithParameters:inputParameters images:image imageParamters:imageParameters];
  }


  • 然后数据(即正文)将如下所示

  • then the data (i.e body) will look like this



  • Content-Type=multipart/form-data; boundary=------CLABoundaryGOKUL
    
    --------CLABoundaryGOKUL
    Content-Disposition: form-data; name=user_id
    
    1
    --------CLABoundaryGOKUL
    Content-Disposition: form-data; name=name
    
    XXX
    --------CLABoundaryGOKUL
    Content-Disposition: form-data; name=img_one; filename=image.jpg
    
    Content-Type:image/jpeg
    
    //First image data appended here
    
    --------CLABoundaryGOKUL
    Content-Disposition: form-data; name=img_two; filename=image.jpg
    
    Content-Type:image/jpeg
    
    //Second image data appended here.
    





    • 以上给出数据将清楚地解释发生了什么,所有参数和密钥都附加在数据中这里您可以找到有关发送multipart / form的更多详细信息。

      • The above give data will clearly explain what going on,all the parameters and keys have been append in the data Here you can find more details about sending multipart/form.


        1. 现在只需将上述数据添加到请求[request setHTTPBody:body];

        2. setURL 在此方法中添加您应用的基本网址。

        3. 现在我们所有人需要做的是建立与服务器的连接并发送请求。我们使用NSURLConnection发送请求。关于NSURLConnection的描述加载URL请求的数据并在操作队列上执行处理程序块时请求完成或失败。

        4. statusCode ,这有助于了解我们是否从服务器获得了成功的响应。如果 200 表示正常,则 500 表示内部服务器错误等。更多详细信息这里

        1. Now simply add the above data to request by [request setHTTPBody:body];
        2. setURL in this method add your base url of your app.
        3. Now all we need to do is make a connection to the server and send the request.Here we use NSURLConnection to send request.Description about NSURLConnection Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
        4. statusCode which helps to find out whether we got successful response from server. If 200 means OK, 500 means Internal Server Error, etc.. more details here .

        处理其他情况下的错误。

        Handle the error in else case.


      • 仅供参考我已经解释了我能做什么,请参考链接以便更好地理解。

        FYI I have explained what i can,refer the links for better understanding.

        编辑:

        只需更改 imageParamater 数组中的名称,即可满足您的要求 img_one& ; img_two 图片

        Just change the name in imageParamater array,To satisfy your requirement changed img_one & img_two with image.

         - (IBAction)Done:(id)sender{
             //Change input parameters as per your requirement.
             NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                          @"1",@"user_id" ,
                                          "XXX",@"name" ,
                                          nil];
            NSArray * image = [NSArray arrayWithObjects:[UIImage imageNamed:@"Test"],nil]; //Change Test with your image name
            NSArray * imageParameters = [NSArray arrayWithObjects:@"image",nil];//Added image as a key.
            [self callApiWithParameters:inputParameters images:image imageParamters:imageParameters];
                      }
        

        和使用示例基本网址更改第6点

        and Change Point 6 with your example base URL,

        // 6

         [request setURL:[NSURL URLWithString:@"http://google.com/files/upload.php?"]];
        

        这篇关于将图像上传到服务器详细说明初学者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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