0

我想上传一个UIImage到服务器。为此,我使用以下代码行::

- (void)imagePickerController:(UIImagePickerController *)picker 
    didFinishPickingImage:(UIImage *)image
              editingInfo:(NSDictionary *)editingInfo
{


imageView.image = image;    

NSData *pngData = UIImagePNGRepresentation(imageView.image);

NSString *imageFile = @"image.png";   
NSString *docDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *filePath = [docDir stringByAppendingPathComponent:imageFile]; 
NSString *dataIS=[NSString base64StringFromData:pngData length:[pngData length]];
[pngData writeToFile:filePath atomically:YES];






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=\"image\"; filename=\"image.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:pngData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];


NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];


[self.parentViewController dismissModalViewControllerAnimated:YES];

}

但是,我在 gdb 中收到以下错误 ::

Your request could not be processed. Request could not be handled.

我也对正确使用感到困惑,urlString即我怀疑我是否正确使用它。

但是,如果我使用以下内容,则urlString可以将图像文件上传到服务器::

NSString *urlString = [NSString stringWithFormat:@"http://xxxx.com/mediawiki/api.php?action=upload&filename=image.png&url=%@&token=%@", url, token] ;

参考APIfor mediawiki(http://www.mediawiki.org/wiki/API:Upload),有人可以帮我整理一下吗?谢谢并恭祝安康。

4

4 回答 4

2

我在上传多个图像和数据时遇到同样的问题,但我使用 AFNetworking 类并将多个图像上传到服务器。

NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"your URL"]];


AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
path = [[NSString alloc] initWithString:[URL absoluteString]];
vdict = @{
            // Your Parameter Pass
        };

[self checkmultiple:vdict];


-(void)checkmultiple:(NSDictionary*)vdict
{

AFHTTPRequestOperation *op = [manager POST:path parameters:vdict constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                              {
                                  for(i = 0;i<[appDelegate.gblarrydata count];i++)
                                  {
                                      NSString *paths = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"New Folder"];
                                      // NSLog(@"%@",paths);
                                      NSString *documentsDirectory = paths;

                                      NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:[[appDelegate.gblarrydata objectAtIndex:i]valueForKey:@"nameimage"]];

                                      NSData *data1 =[[NSData alloc]initWithContentsOfFile:getImagePath];
                                      NSString *data2 =[[appDelegate.gblarrydata objectAtIndex:i] valueForKey:@"Note"];

                                      [formData appendPartWithFileData:data1 name:[NSString stringWithFormat:@"pimage%d",i+1] fileName:[NSString stringWithFormat:@"pimage%d.jpg",i+1] mimeType:@"image/jpeg"];

                                      if(![data2 isEqualToString:@""])
                                      {
                                          [formData appendPartWithFormData:[data2 dataUsingEncoding:NSUTF8StringEncoding]
                                                                      name:[NSString stringWithFormat:@"pnotes%d",i+1]];
                                      }


                                  }


                              }
                             success:^(AFHTTPRequestOperation *operation, id responseObject)
                              {
                                  NSLog(@"Upload success");

                                  NSString *returnString = [NSString stringWithFormat:@"%@",[responseObject JSONRepresentation]];
                                  NSLog(@"Reg Date:%@",returnString);

                              }

                             failure:^(AFHTTPRequestOperation *operation, NSError *error)
                              {
                                  NSLog(@"Error:%@",error);
                              }];
[op start];

} 
于 2014-08-27T10:38:18.753 回答
1

我有同样的问题。我使用 ASIHTTPRequest来上传文件,它工作正常。

上传:

图像文件:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:@"Ben" forKey:@"names"];
[request addPostValue:@"George" forKey:@"names"];
[request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"];
[request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"];

同时使用其他数据:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

// Upload a file on disk
[request setFile:@"/Users/ben/Desktop/ben.jpg" withFileName:@"myphoto.jpg" andContentType:@"image/jpeg"
forKey:@"photo"];

// Upload an NSData instance
[request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"];

下载到所需路径:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/Users/ben/Desktop/my_file.txt"];
于 2013-01-06T08:16:54.197 回答
0

如果要将图像发送到服务器,以编码形式发送数据,服务器可以处理图像的编码形式,他们将从编码中获取图像数据。

于 2012-07-18T09:08:58.573 回答
0

// UIImage * img = [UIImage imageNamed:@"min.png"];

// NSData *imageData = UIImageJPEGRepresentation(img,0.2);

NSString *strUrl =[NSString stringWithFormat:@"%@/upload_file.php", [globalApp sharedUser].vg_dominio ];
//strUrl = @"http://192.168.1.100/mismedicinas/upload_file.php";

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
request.HTTPMethod = @"POST";
request.timeoutInterval = 60;
request.HTTPShouldHandleCookies = false;

//[request setHTTPMethod:@"POST"];


NSString *boundary = @"----------SwIfTeRhTtPrEqUeStBoUnDaRy";

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];

[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
//[request addValue:contentType forHTTPHeaderField:@"Content-Type"];



NSMutableData *body = [NSMutableData data];
NSMutableData *tempData = [NSMutableData data];

[tempData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[tempData appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"iphoneimage.xml\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[tempData appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//[tempData appendData:[NSData dataWithData:imageData]];  ///IMAGEN
[tempData appendData:[NSData dataWithData:cData]];

[tempData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData: tempData];


[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];



[request setValue: [NSString stringWithFormat:@"%d", body.length ] forHTTPHeaderField:@"Content-Length"];


request.HTTPBody =body;





NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(@"finalizacion %@", returnString);
于 2014-09-25T01:06:47.623 回答