ios 从iOS上传图片到PHP服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20728317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload image to the PHP server from iOS
提问by Vinay Jain
I know this question has been asked earlier as well but my issue is a bit different.
我知道之前也有人问过这个问题,但我的问题有点不同。
I want to upload an image to the PHP server and i want to send more parameters along with an image from an iOS. I searched on the google and found two solutions:
我想将图像上传到 PHP 服务器,并且我想从 iOS 发送更多参数以及图像。我在谷歌上搜索,找到了两个解决方案:
Either we will send an image as
Base64
encoded string inJSON
. Referred link.Or we will upload an image to server using form data. I have referred this link. If someone refers me this way, then please help me to add more parameters in this API.
要么我们将图像作为
Base64
编码字符串发送到JSON
. 参考链接。或者我们将使用表单数据将图像上传到服务器。我已经提到了这个链接。如果有人以这种方式引用我,那么请帮助我在此 API 中添加更多参数。
Now my question is, which one is the best way to upload an image to the server and i have to send more parameters (username, password and more details) in the same web service call.
现在我的问题是,哪一种是将图像上传到服务器的最佳方式,我必须在同一个 Web 服务调用中发送更多参数(用户名、密码和更多详细信息)。
Thanks in advance.
提前致谢。
回答by Nitin Gohel
You can upload image from iOS App to PHP server
like this two way:
您可以通过PHP server
以下两种方式从 iOS 应用上传图像:
Using New AFNetworking:
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
NSString *stringUrl =@"http://www.myserverurl.com/file/uloaddetails.php?"
NSString *string =@"http://myimageurkstrn.com/img/myimage.png"
NSURL *filePath = [NSURL fileURLWithPath:string];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:userid,@"id",String_FullName,@"fname",String_Email,@"emailid",String_City,@"city",String_Country,@"country",String_City,@"state",String_TextView,@"bio", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:stringUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileURL:filePath name:@"userfile" error:nil];//here userfile is a paramiter for your image
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(@"%@",[responseObject valueForKey:@"Root"]);
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:@"myappname" message:string delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
Alert_Success_fail = [[UIAlertView alloc] initWithTitle:@"myappname" message:[error localizedDescription] delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[Alert_Success_fail show];
}];
Second use NSURLConnection:
第二次使用 NSURLConnection:
-(void)uploadImage
{
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *urlString = [ NSString stringWithFormat:@"http://yourUploadImageURl.php?intid=%@",1];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", 1]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
This both way working fine for uploading image from app to php server hope this helps for you.
这两种方式都可以很好地将图像从应用程序上传到 php 服务器,希望这对您有所帮助。
回答by Segev
Using AFNetworkingthis is how I do it:
使用AFNetworking这就是我的做法:
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setObject:@"myUserName" forKey:@"username"];
[params setObject:@"1234" forKey:@"password"];
[[AFHTTPRequestOperationLogger sharedLogger] startLogging];
NSData *imageData;
NSString *urlStr = [NSString stringWithFormat:@"http://www.url.com"];
NSURL *url = [NSURL URLWithString:urlStr];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
imageData = UIImageJPEGRepresentation(mediaFile, 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:nil parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:imageData name:@"mediaFile" fileName:@"picture.png" mimeType:@"image/png"];
}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"File was uploaded" message:@""
delegate:self cancelButtonTitle:@"Close" otherButtonTitles: nil];
[alert show];
}
failure:^(NSURLRequest *request , NSURLResponse *response , NSError *error , id JSON)
{
NSLog(@"request: %@",request);
NSLog(@"Failed: %@",[error localizedDescription]);
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
{
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];
回答by korat prashant
Try with Restkit
尝试使用 Restkit
Here is link Restkit image upload with parameter
You can get Restkit help from here Restkit integration step
您可以从此处获取 Restkit 帮助Restkit 集成步骤
回答by Anilkumar iOS ReactNative
Try this.
尝试这个。
-(void)EchoesPagePhotosUpload
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
[self startIndicator];
});
//NSLog(@"%@",uploadPhotosArray);
NSMutableArray *uploadPhotosByteArray=[[NSMutableArray alloc] init];
conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:0]];
NSLog(@"conversionImage.size.height %f",conversionImage.size.height);
NSLog(@"conversionImage.size.width %f",conversionImage.size.width);
if(conversionImage.size.height>=250&&conversionImage.size.width>=250)
{
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self performSelectorInBackground: @selector(LoadForLoop) withObject: nil]; NSLog(@"conversionImage.size.height %f",conversionImage.size.height);
NSLog(@"conversionImage.size.width %f",conversionImage.size.width);
for(int img_pos=0;img_pos<[uploadPhotosArray count];img_pos++)
{
conversionImage= [UIImage imageWithContentsOfFile:[uploadPhotosArray objectAtIndex:img_pos]];
NSData *imageData = UIImageJPEGRepresentation(conversionImage,1.0);
[Base64 initialize];
NSString *uploadPhotoEncodedString = [Base64 encode:imageData];
//NSLog(@"Byte Array %d : %@",img_pos,uploadPhotoEncodedString);
[uploadPhotosByteArray addObject:uploadPhotoEncodedString];
}
dispatch_async(dispatch_get_main_queue(), ^{
NSString *photo_description=[webview stringByEvaluatingJavaScriptFromString: @"document.getElementById('UploadPicsDesc').value"];
NSString *uploadPhotoImageName=@"uploadPhoto.jpg";
NSDictionary *UploadpicsJsonResponseDic=[WebserviceViewcontroller EchoesUploadPhotos:profileUserId imageName:uploadPhotoImageName Image:uploadPhotosByteArray PhotoDescription:photo_description];
//NSLog(@"%@",UploadpicsJsonResponseDic);
NSString *UploadPhotosStatusString=[UploadpicsJsonResponseDic valueForKey:@"Status"];
NSLog(@"UploadPhotosStatusString :%@",UploadPhotosStatusString);
NSString *uploadPhotosCallbackstring=[NSString stringWithFormat:@"RefreshForm()"];
[webview stringByEvaluatingJavaScriptFromString:uploadPhotosCallbackstring];
});
});
}
else {
UIAlertView *ErrorAlert=[[UIAlertView alloc] initWithTitle:@"Error" message:@"Please Upload Photo Above 250x250 size" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[ErrorAlert show];
NSLog(@"conversionImage.size.height %f",conversionImage.size.height);
NSLog(@"conversionImage.size.width %f",conversionImage.size.width);
}
}
回答by razesh
-(void)uploadImage
{
NSString *mimetype = @"image/jpeg";
NSString *myimgname = _txt_fname.text; //@"img"; //upload image with this name in server PHP FILE MANAGER
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *imageDataa = UIImagePNGRepresentation(chooseImg.image);
NSDictionary *parameters =@{@"fileimg":defaults }; //@{@"uid": [uidstr valueForKey:@"id"]};
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
//here post url and imagedataa is data conversion of image and fileimg is the upload image with that name in the php code
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:@"POST" URLString:@"http://posturl/newimageupload.php"
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageDataa
name:@"fileimg"
fileName:myimgname
mimeType:mimetype];
}];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success %@", responseObject);
[uploadImgBtn setTitle:@"Uploaded" forState:UIControlStateNormal];
[chooseImg setImage:[UIImage imageNamed:@"invoice-icon.png"]];
if([[responseObject objectForKey:@"status"] rangeOfString:@"Success"].location != NSNotFound)
{
[self alertMsg:@"Alert" :@"Upload sucess"];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure %@", error.description);
[chooseImg setImage:[UIImage imageNamed:@"invoice-icon.png"]];
uploadImgBtn.enabled = YES;
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
float myprog = (float)totalBytesWritten/totalBytesExpectedToWrite*100;
NSLog(@"Wrote %f ", myprog);
}];
// 5. Begin!
[operation start];
}
回答by kalpesh
Try this this is work for me.
试试这个,这对我有用。
NSData *postData = [Imagedata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:apiString]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDictft = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];