首页 / IOS / 将图像从iOS上传到PHP
将图像从iOS上传到PHP
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了将图像从iOS上传到PHP,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4967字,纯文字阅读大概需要8分钟。
内容图文
![将图像从iOS上传到PHP](/upload/InfoBanner/zyjiaocheng/704/40d46f5005434b628d29d33d4121db20.jpg)
我正在尝试通过PHP将图像从我的iOS App上传到我的Web服务器.这是以下代码:
-(void)uploadImage {
NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
//1
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//2
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSString *urlString = @"http://mywebserver.com/script.php";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[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 *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"iosfile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"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];
//3
self.uploadTask = [defaultSession uploadTaskWithRequest:request fromData:imageData];
//4
self.progressBarView.hidden = NO;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
//5
[uploadTask resume];
}
// update the progressbar
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
dispatch_async(dispatch_get_main_queue(), ^{
[self.progressBarView setProgress:(double)totalBytesSent / (double)totalBytesExpectedToSend animated:YES];
});
}
// when finished upload
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
self.progressBarView.hidden = YES;
[self.progressBarView setProgress:0.0];
});
if (!error) {
// no error
NSLog(@"no error");
} else {
NSLog(@"error");
// error
}
}
以下是简单的PHP代码:
<?php
$msg = " ".var_dump($_FILES)." ";
$new_image_name = $_FILES["userfile"]["name"];
move_uploaded_file($_FILES["userfile"]["tmp_name"], getcwd() . "/pictures/" . $new_image_name);
?>
iOS上的应用程序似乎上传了照片,进度条正在运行,但是当我检查服务器文件时,我的文件并没有真正上传.
当我使用以下代码发送图片时,它完美地工作(编辑:但没有进度条):
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
并且想到我错了?
解决方法:
最后我用AFNetworking库来处理这个问题.由于我还没有找到明确的方法在网络和stackoverflow上执行此操作,这里是我的答案,通过PHP轻松地将用户的图像从他们的iOS设备发布到您的服务器.大部分代码来自this stackoverflow post.
-(void)uploadImage {
image = [self scaleImage:image toSize:CGSizeMake(800, 800)];
NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
// 1. Create `AFHTTPRequestSerializer` which will create your request.
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSDictionary *parameters = @{@"your_param": @"param_value"};
NSError *__autoreleasing* error;
// 2. Create an `NSMutableURLRequest`.
NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:@"http://www.yoururl.com/script.php" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:@"userfile"
fileName:@"image.jpg"
mimeType:@"image/jpg"];
} error:(NSError *__autoreleasing *)error];
// 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *operation =
[manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure %@", error.description);
}];
// 4. Set the progress block of the operation.
[operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
long long totalBytesWritten,
long long totalBytesExpectedToWrite) {
//NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
[self.progressBarView setProgress:(double)totalBytesWritten / (double)totalBytesExpectedToWrite animated:YES];
}];
// 5. Begin!
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
self.progressView.hidden = NO;
[operation start];
}
我认为这将有助于新的xcoders.
干杯.
内容总结
以上是互联网集市为您收集整理的将图像从iOS上传到PHP全部内容,希望文章能够帮你解决将图像从iOS上传到PHP所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。