//Init the NSURLSession with a configurationNSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];//Create an URLRequestNSURL *url = [NSURL URLWithString:@"yourURL"];NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];//Create POST Params and add it to httpBodyNsstring *params = @"API_key=APIKEY&email=example@example.com&password=password";[urlRequest sethttpMethod:@"POST"];[urlRequest sethttpBody:[params dataUsingEnCoding:NSUTF8StringEnCoding]];//Create taskNSURLSessionDataTask *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 hereNSURL* requestURL = [NSURL URLWithString:@""]; // create requestNSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];[request sethttpShouldHandlecookies:NO];[request setTimeoutInterval:30];[request sethttpMethod:@"POST"];// set Content-Type in http headerNsstring *ContentType = [Nsstring stringWithFormat:@"multipart/form-data; boundary=%@",BoundaryConstant];[request setValue:ContentType forhttpheaderFIEld: @"Content-Type"];// post bodyNSMutableData *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 dataNSData *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-lengthNsstring *postLength = [Nsstring stringWithFormat:@"%d",[body length]];[request setValue:postLength forhttpheaderFIEld:@"Content-Length"];// set URL[request setURL:requestURL];
但我的观点是我正在自学,对于没有解释的初学者来说很难理解所以我所要求的只是一个解释,一个关于整个过程的细节解释如果有人很难花在这上面问题,因为不管你信不信,我发现这是迄今为止最困难的话题,因为主要原因是没有关于整个过程的教程,如果有人能够现在迈出一步并解释这个概念,那么对初学者也没有任何解释对将要学习明天的学生.因此,任何能够详细解释这一点的人以及上传过程如何运作以及参考的一些步骤将不胜感激.
解决方法 这里我们将看一下图像上传以及一些**参数,因为大多数时候我们上传图像以及一些参数,例如userID.Note : ConsIDer I Have an API and a Key “image” .
>在深入讨论我们的主题之前,让我提供执行内容的代码source,我们将在下面看到的所有详细信息都来自其他一些堆栈溢出线程和其他站点的一些,我将提供所有链接供您参考.
-(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 **因为我们要向它附加一些数据.如果您需要对可变网址请求进行一些深入的澄清,请通过此documentation.
> sethttpShouldHandlecookies在这里我们要决定是否要使用cookies.了解更多关于visit
> setTimeoutInterval这有助于为url request设置时间限制.在给定时间后添加时间间隔(以秒为单位),请求将被终止.
> sethttpMethod有many个方法.但是在很多情况下我们使用GET和POST方法.POST和GET之间的差异是here和here
> Boundary有助于将参数彼此分离,以便服务器可以识别它们.边界可以是您希望随意编辑它的任何内容.
>这里我们使用multipart / form-data; boundary = as content type.要知道我们为什么要这个内容类型看看this线程.
> NSMutableData * body我们将所有参数和值附加到此数据,然后将sethttpBody附加到UrlRequest.
>如果这是我们称之为’callAPIWithParameters’的方法
- (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]; }
>然后数据(即正文)将如下所示
06002
>以上给出的数据将清楚地说明发生了什么,所有的参数和键都附加在数据Here中,你可以找到有关发送multipart / form的更多细节.
>现在只需通过[request sethttpBody:body]将上述数据添加到请求中;
>此方法中的setURL会添加您应用的基本网址.
>现在我们需要做的就是建立与服务器的连接并发送请求.我们使用NSURLConnection发送request.Description关于NSURLConnection加载URL请求的数据并在请求完成时在 *** 作队列上执行处理程序块或失败.
> statusCode有助于确定我们是否从服务器获得了成功的响应.如果200表示正常,则500表示内部服务器错误等.更多细节here.
>处理其他情况下的错误.
仅供参考我已经解释了我能做什么,请参考链接以便更好地理解.
编辑:
只需更改imageParamater数组中的名称,即可满足您的要求img_one& img_two与图像.
- (IBAction)Done:(ID)sender{ //Change input parameters as per your requirement. NSDictionary * inputParameters = [NSDictionary dictionaryWithObjectsAndKeys: @"1",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更改Point 6,
// 6
[request setURL:[NSURL URLWithString:@"http://Google.com/files/upload.PHP?"]];总结
以上是内存溢出为你收集整理的ios – 将图像上传到服务器详细说明初学者全部内容,希望文章能够帮你解决ios – 将图像上传到服务器详细说明初学者所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)