当前位置: 首页 > 知识库问答 >
问题:

将图像上传到服务器详细说明

祝宾白
2023-03-14
    //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];
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];

但我的观点是,我是靠自己学习的,如果没有解释,初学者很难理解,所以我所要求的只是一个解释,对整个过程的详细解释如果有人很难花时间在这个问题上,因为信不信由你,我发现这是到目前为止最难的话题,因为主要原因是没有关于整个过程的教程,也没有对初学者的解释,如果有人现在能解释概念,对明天将要学习的学生来说会更容易。因此,任何人谁可以解释这详细和如何上传过程的工作和一些步骤,以供参考,将非常感谢。

注意:假设我有一个API和一个关键字“image”。

共有1个答案

许奇
2023-03-14

在这里,我们将看看图像上传和一些**参数,因为大多数时候我们上传图像和一些参数,如userid。

>

  • 在深入到我们的主题之前,让我提供做东西源码的代码,下面我们将看到的所有细节都来自其他一些堆栈溢出线程和其他网站,我将提供所有链接供您参考。

    -(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);
                           }
                       }];
    
    
     }
    

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

    • 我们使用**nsmutableurlrequest**而不是**nsurlrequest**,因为我们要向它附加一些数据。
      • 这里我们必须决定是否要使用cookie。要了解更多信息,请访问
      • setTimeoutInterval这有助于设置url请求的时间限制。在给定时间后以秒为单位添加时间间隔,请求将被终止。
      • SethTtpMethod有很多方法。但是我们在很多情况下都使用GET和POST方法。POST和GET的区别在于这里和这里

      NSMutableData*body我们将把所有的参数和值附加到这个数据中,然后把setHTTPBody附加到urlrequest中。

      >

    • 如果这是调用'call apiWithParameters‘方法的方式

       - (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];
        }
      

      那么数据(即主体)将如下所示

      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.
      

      >

    • 上面给出的数据将清楚地解释发生了什么,所有的参数和键都已经附加在数据中,在这里你可以找到更多关于发送多部分/表单的细节。

      statusCode,它帮助发现我们是否从服务器获得了成功的响应。如果200表示OK,500表示内部服务器错误等。更多细节在这里。

      在else情况下处理错误。

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

      编辑:

      只需更改imageParamater数组中的名称,即可满足使用Image更改img_one和img_two的要求。

       - (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];
                    }
      

      并使用示例基URL更改第6点,

      //6

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

  •  类似资料:
    • 问题内容: 我想随请求一起发送图像作为参数。我使用下面的代码调用POST请求,但是我不知道如何将图像追加到正文中。 我通过图像选择器获取图像,如下所示: 我的要求如下 我是Swift的新手。我已经通过multipart / form-data看到了这一点,但无法自己实现。我不想将其编码为基本64格式。请帮助我。 问题答案: 我使用以下结构发送图像: 然后在函数中创建如下主体:

    • 问题内容: 我需要即时将画布图像数据上传到服务器(数据库),即,我需要创建一个带有input=file的表单,并在没有任何用户交互的情况下发布图像数据。 问题答案: 您不需要文件输入,只需使用Ajax 获取数据并将其发布到服务器即可。 请参阅MDN文档。 但是即使使用,您也无法在IE中获取图像数据。

    • 我必须上传从用户首选的应用程序(Cameta,画廊等)选择后的图像文件。我可以在Imageview中显示结果意图为位图。现在我想上传这个图像后,一个按钮将被点击。我用改装来做到这一点。我跟随ImagePicker类将图像收集到我的Imageview中。 正在收集图像代码: 要将图像上载到服务器,我使用改装库 API接口 我的问题是,在将result intent中的Imageview设置为在服务器

    • 我正在用Laravel5.6构建一个表单,在其中我保存了一个名字和一个用户照片,但我需要将照片与用户名一起存储。我展示了我商店的代码 我可以使用$request->nombre获得用户名; 但我不知道怎么给照片取名字

    • 我已经为KeystoneJS的AdminUI编写了一个自定义字段,它使用了TinyMCE的编辑器。 KeystoneJS在下面运行Apollo GraphQL服务器,并根据CMS模式自动生成变化和查询。TinyMCE具有输入自定义挂钩以上载图像的功能。 我希望能够连接这两个——使用GraphQL将图像从TinyMCE上传到KeystoneJS的服务器。 例如,在我的设置中,我在CMS中有一个字段。

    • 问题内容: 我要上传图像并将其保存在服务器中。我上传了图像并获得了预览,但是我被困在将图像发送到服务器上。我想使用角度服务将此图像发送到服务器。 这是HTML代码 这是指令 问题答案: 假设您在后端中期望Multipart,这是一段对我有用的代码。 这是一个jsfiddle。 请注意 以下部分: 是一些Angular魔术,为了使$ http解析FormData并找到正确的内容类型,等等。