猿问
下载APP

iPhone编程中文件上传到HTTP服务器

iPhone编程中文件上传到HTTP服务器

有人能给我提供一些链接或示例来使用iPhoneAPI将文件上传到HTTP服务器。


白衣染霜花
浏览 58回答 3
3回答

慕田峪9158850

下面的代码使用HTTPPOST将NSData发布到Web服务器。您还需要一些PHP方面的知识。NSString *urlString = @"http://yourserver.com/upload.php";NSString *filename = @"filename";request= [[[NSMutableURLRequest alloc] init] autorelease];[request setURL:[NSURL URLWithString:urlString]];[request setHTTPMethod:@"POST"];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]];[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];[postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];[postbody appendData:[NSData dataWithData:YOUR_NSDATA_HERE]];[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];[request setHTTPBody:postbody];NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];NSLog(@"%@", returnString);

慕仰0522570

ASIHTTPRequest是一个很好的网络API包装,使上传文件非常容易。下面是他们的例子(但你也可以在iPhone上这样做-我们将图像保存到“磁盘”中,然后上传。ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];[request setPostValue:@"Ben" forKey:@"first_name"]; [request setPostValue:@"Copsey" forKey:@"last_name"];[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

料青山看我应如是

我用ASIHTTPRequest很像简销售答案但是它已经不在开发中了,作者建议使用其他库,比如AFNetwork。老实说,我认为现在是时候开始寻找其他地方了。AFNetwork工作很棒,让你大量使用积木(这是一个很大的解脱)。下面是他们的文档页面上的图片上传示例GitHub:NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {&nbsp; &nbsp; [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];}];AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {&nbsp; &nbsp; NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);}];[httpClient enqueueHTTPRequestOperation:operation];
打开App,查看更多内容
随时随地看视频慕课网APP
我要回答