嗨,我有一个接受多部分对象的后端。我正在努力寻找将图像发布为多部分对象并将其作为参数传递给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

最佳答案

我选择了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);
 }];

07-24 09:24