我有以下android代码,工作完美:
DefaultHttpClient client = new DefaultHttpClient(UploadPostActivity.this);
String s = "http://dacaea28.ngrok.io/my-site/multipart.php";
URL url = new URL(s);
String filepath = "/sdcard/Download/images.jpg";
File file = new File(filepath);
FileBody cbFile = new FileBody(file);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
org.apache.http.client.methods.HttpPost post = new org.apache.http.client.methods.HttpPost(s);
mpEntity.addPart("image",cbFile);
mpEntity.addPart("name", new StringBody("Test", Charset.forName("UTF-8")));
mpEntity.addPart("data", new StringBody("This is test report", Charset.forName("UTF-8")));
org.apache.http.HttpResponse response = null;
post.setEntity(mpEntity);
org.apache.http.HttpResponse response1 = client.execute(post);
String t = EntityUtils.toString(response1.getEntity());
Log.d("Response:", t);
我使用的PHP代码:
<?php
//Receive the data from android
$name = $_POST['name'];
$data = $_POST['data'];
if(empty($_FILES))
{
echo json_encode(
array(
'msg1'=>'file array is empty'
)
);
}
else if(!isset($_FILES['image']))
{
echo json_encode(
array(
'msg2'=>'image is not being set'
)
);
}
else
{
$file = $_FILES['image'];
$file2 = $_FILES['doc'];
//echo json_encode(
// array(
// 'result'=>'success adding $name , $data and $file',
// 'msg'=>'Report added successfully.'
// )
// );
$size = $file['size'];
echo "Name is $name and file size is $size";
$info = pathinfo($file['name']);
$ext = $info['extension']; // get the extension of the file
$newname = $file['name'];
$target = '/Applications/MAMP/htdocs/my-site/images/'.$newname;
move_uploaded_file( $file['tmp_name'], $target);
echo "Name is $name, file size is $size, extension is $ext, new file name is $newname and finally target is $target";
$size2 = $file2['size'];
echo "Name is $name and file size is $size";
$info2 = pathinfo($file2['name']);
$ext2 = $info2['extension']; // get the extension of the file
$newname2 = $file2['name'];
$target2 = '/Applications/MAMP/htdocs/my-site/images/'.$newname2;
move_uploaded_file( $file2['tmp_name'], $target2);
echo "Name is $name, file size is $size, extension is $ext, new file name is $newname and finally target is $target";
}
?>
现在对应的iOS代码不为我工作并返回'msg1'=>'文件数组为空'
我正在使用从图库中选择图像并试图上传它。
#import "UploadViewController.h"
@interface UploadViewController ()<NSURLSessionDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation UploadViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (IBAction)uploadData:(id)sender {
const NSString *boundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
const NSString *fileParamConstant = @"image";
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
NSURL* requestURL = [NSURL URLWithString:@"http://dacaea28.ngrok.io/my-site/multipart.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:requestURL];
[request setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundaryConstant];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSData *imageData = UIImageJPEGRepresentation(self.imageView.image,0.9);
// NSLog(@"image data added %lu",self.imageView.image.size);
if (imageData) {
[body appendData:[[NSString stringWithFormat:@"--%@rn", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="%@"; filename="%@"rn", fileParamConstant, @"filename"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--rn", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:@"%zu", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:body];
[request addValue:@"Test" forHTTPHeaderField:@"name"];
[request addValue:@"Test2" forHTTPHeaderField:@"data"];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"STRING %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSLog(@"%@", response);
NSLog(@"%@", error);
}];
[uploadTask resume];
}
- (IBAction)pickImage:(id)sender {
UIImagePickerController *pickerController = [[UIImagePickerController alloc]
init];
pickerController.delegate = self;
[self presentViewController:pickerController animated:YES completion:nil];
}
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
self.imageView.image = image;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
请让我知道我的objc代码中缺少哪一部分
下面是一个简短的列表:
- 您需要在每个块中包含 Content-Type 和 Content-Disposition头。(你本来有两个,但注释掉了)
- 每组标头必须以两个
rn
对结尾,而不是一个。(原始代码在这方面是正确的,但被注释掉了。) - 你原来附加它与表单字段名"照片"而不是"图像"作为Android和PHP代码正在使用。这是正确的。
- 一开始不需要在请求上设置Content-Length;
- 你的脚本希望上传两个文件,而你只附加了一个。
这可能是一个不完整的列表,所以即使在您修复它们之后,这也可能不起作用。我通常建议开发人员跳过表单数据编码,而使用URL编码进行上传,这是有原因的。它的效率略低,但编写起来要简单得多。: -)
无论如何,我强烈建议你运行Charles Proxy并将网页浏览器或Android应用程序指向它并查看发送的内容,然后在iOS上做同样的操作,并比较两者。这将使大多数或所有的错误更容易被发现。
My final working code so I can find it later:
#import "UploadViewController.h"
@interface UploadViewController ()<NSURLSessionDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation UploadViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (IBAction)uploadData:(id)sender {
const NSString *boundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
const NSString *fileParamConstant = @"image";
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
NSURL* requestURL = [NSURL URLWithString:@"http://d7e79f94.ngrok.io/my-site/multipart.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:requestURL];
[request setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundaryConstant];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSData *imageData = UIImageJPEGRepresentation(self.imageView.image,0.9);
// NSLog(@"image data added %lu",self.imageView.image.size);
if (imageData) {
[body appendData:[[NSString stringWithFormat:@"--%@rn", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="%@"; filename="%@"rn", fileParamConstant, @"image.jpg"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpegrnrn" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"rn"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--rn", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:@"%zu", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:body];
[request addValue:@"Test" forHTTPHeaderField:@"name"];
[request addValue:@"Test2" forHTTPHeaderField:@"data"];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"STRING %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSLog(@"%@", response);
NSLog(@"%@", error);
}];
[uploadTask resume];
}
- (IBAction)pickImage:(id)sender {
UIImagePickerController *pickerController = [[UIImagePickerController alloc]
init];
pickerController.delegate = self;
[self presentViewController:pickerController animated:YES completion:nil];
}
- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
self.imageView.image = image;
[self dismissViewControllerAnimated:NO completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end