//原生上传方式:
- ( IBAction )uploadButton:( id )sender {
UIImage *image = [ UIImage imageNamed : @"1.jpg" ]; // 图片名
NSData *imageData = UIImageJPEGRepresentation (image, 0.5 );// 压缩比例
NSLog ( @" 字节数 :%i" ,[imageData length]);
// post url
NSString *urlString = @"http://192.168.1.113:8090/text/UploadServlet" ;
// 服务器地址
// setting up the request object now
NSMutableURLRequest *request = [[ NSMutableURLRequest alloc ] init ] ;
[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 : @"Content-Disposition:form-data; name=\"userfile\"; filename=\"2.png\"\r\n" ] 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];
// NSLog(@"1-body:%@",body);
NSLog ( @"2-request:%@" ,request);
NSData *returnData = [ NSURLConnection sendSynchronousRequest :request returningResponse :nil error : nil ];
NSString *returnString = [[ NSString alloc ] initWithData :returnData encoding :NSUTF8StringEncoding ];
NSLog ( @"3- 测试输出: %@" ,returnString );
}
下面两个函数是可以用的:
[formData appendPartWithFileData:<#(NSData *)#> name:<#(NSString *)#> fileName:<#(NSString *)#> mimeType:<#(NSString *)#>]
[formData appendPartWithFileURL:<#(NSURL *)#> name:<#(NSString *)#> error:<#(NSError *__autoreleasing *)#>]
[formData appendPartWithFileURL:<#(NSURL *)#> name:<#(NSString *)#> fileName:<#(NSString *)#> mimeType:<#(NSString *)#> error:<#(NSError *__autoreleasing *)#>]
这个函数,我用时失败:
[formData appendPartWithFormData:<#(NSData *)#> name:<#(NSString *)#>]
保存图像:
- (void)viewDidLoad { [super viewDidLoad]; // 保存每次添加的图片 self.imageDataArray = [NSMutableArray array]; }
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *originalImage = [info valueForKey:UIImagePickerControllerEditedImage] ; // 得到图片的缓存数据 NSData * imagedata = UIImageJPEGRepresentation([originalImage imageByScalingAndCroppingForSize:CGSizeMake(originalImage.size.width, originalImage.size.height)], 0.5); static int index = 1; NSString * newImageName = [NSString stringWithFormat:@"%@%zi%@", Image_Name, index, @".jpg"]; NSString *jpgPath = NSHomeDirectory(); jpgPath = [jpgPath stringByAppendingPathComponent:@"Documents"]; jpgPath = [jpgPath stringByAppendingPathComponent:newImageName]; [imagedata writeToFile:jpgPath atomically:YES]; [self.imageDataArray addObject:imagedata]; index ++ ; // 显示当前上传图片 [self showUploadImage:imagedata]; [picker dismissViewControllerAnimated:YES completion:^{ }]; }
// 向服务器提交图片
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// 显示进度
[manager POST:urlstr parameters:[self Params] constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
static int nindex = 1;
// 单张图片上传
NSString * paramName = [NSString stringWithFormat:@"%@%zi", Image_Name, nindex];
NSString * newImageName = [NSString stringWithFormat:@"%@.jpg", paramName];
NSString * imagepath = NSHomeDirectory();
NSString * path = [imagepath stringByAppendingPathComponent:@"Documents"];
NSBundle * Bundle = [NSBundle bundleWithPath:path];
NSURL * fileURL = [Bundle URLForResource:newImageName withExtension:nil];
[formData appendPartWithFileURL:fileURL name:paramName error:nil];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"完成 %@", result);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"错误 %@", error.localizedDescription);
}];
// 向服务器提交图片
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// 显示进度
[manager POST:urlstr parameters:[self Params] constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
// 上传 多张图片
for(NSInteger i = 0; i < self.imageDataArray.count; i++)
{
NSData * imageData = [self.imageDataArray objectAtIndex: i];
// 上传的参数名
NSString * Name = [NSString stringWithFormat:@"%@%zi", Image_Name, i+1];
// 上传filename
NSString * fileName = [NSString stringWithFormat:@"%@.jpg", Name];
[formData appendPartWithFileData:imageData name:Name fileName:fileName mimeType:@"image/jpeg"];
}
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"完成 %@", result);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"错误 %@", error.localizedDescription);
}];
// 向服务器提交图片 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 显示进度 [manager POST:urlstr parameters:[self Params] constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { if (mediaDatas.count > 0) { NSObject *firstObj = [mediaDatas objectAtIndexSafe:0]; if ([firstObj isKindOfClass:[UIImage class]]) {// 图片 for(NSInteger i=0; i<mediaDatas.count; i++) { UIImage *eachImg = [mediaDatas objectAtIndexSafe:i]; //NSData *eachImgData = UIImagePNGRepresentation(eachImg); NSData *eachImgData = UIImageJPEGRepresentation(eachImg, 0.5); [formData appendPartWithFileData:eachImgData name:[NSString stringWithFormat:@"img%d", i+1] fileName:[NSString stringWithFormat:@"img%d.jpg", i+1] mimeType:@"image/jpeg"]; } }else {// 视频 ALAsset *asset = [mediaDatas objectAtIndexSafe:0]; NBLog(@"asset=%@, representation=%@, url=%@", asset, [asset defaultRepresentation], [asset defaultRepresentation].url); if (asset != nil) { NSString *videoPath = [NSDocumentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.mov", 0]]; // 这里直接强制写一个即可,之前计划是用i++来区分不明视频 NSURL *url = [NSURL fileURLWithPath:videoPath]; NSError *theErro = nil; BOOL exportResult = [asset exportDataToURL:url error:&theErro]; NBLog(@"exportResult=%@", exportResult?@"YES":@"NO"); NSData *videoData = [NSData dataWithContentsOfURL:url]; [formData appendPartWithFileData:videoData name:@"video1" fileName:@"video1.mov" mimeType:@"video/quicktime"]; NBLog(@"method 2"); } } } } success:^(AFHTTPRequestOperation *operation, id responseObject) { NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; NSLog(@"完成 %@", result); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"错误 %@", error.localizedDescription); }];