0

嗨,我有一个接受多部分对象的后端。我正在努力寻找将图像作为多部分对象发布并将其作为参数传递给 spring mvc 控制器所涉及的方向/必要步骤。我已经在网上搜索了无数个小时,但仍在努力掌握它。

基本上我是一名 ios 开发人员,我们有一个 spring 后端。我需要将图像作为多部分对象发送,因为它需要作为参数存储在后端。

我正在阅读AFNetworking但我仍然不确定。后端是在设计应用程序之前创建的(后端已外包)所以现在我正在尝试连接到那里。

如果需要,我可以提供更多信息。

我尝试了 Anand K 下面的代码,但现在我得到HTTP Status 500了响应:

Request processing failed; 
nested exception is org.springframework.web.multipart.MultipartException: 
The current request is not a multipart request

以及其他一些“垃圾”

基于 Adnan Ks 建议的新更新*

UIImage *image=[UIImage imageNamed:@"dub.png"];
NSData *imageData=UIImagePNGRepresentation(image);

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://website.com/upload/uploadOneBook.app?userID=12345&uploadFile="]];
[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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"attachement\"; filename=\"%@\";",@"Image.png" ] dataUsingEncoding:NSUTF8StringEncoding]];

[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];


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

NSLog(@"returnString=%@",returnString);

returnString 包含:`HTTP Status 400 - Required MultipartFile parameter 'uploadFile' is not present

4

1 回答 1

1

我选择AFNetworking了一个非常好的多部分对象示例。

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];

[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
      [formData appendPartWithFileURL:filePath name:@"image" error:nil];
     } success:^(AFHTTPRequestOperation *operation, id responseObject) {
      NSLog(@"Success: %@", responseObject);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"Error: %@", error);
 }];
于 2013-11-21T14:03:08.867 回答