2013-11-14 53 views
0

嗨我有一個接受多部分對象的後端。我努力尋找方向/必要的步驟,將圖像作爲多部分對象發佈,並將其作爲參數傳遞給彈簧mvc控制器。我已經在網絡上搜索了無數個小時,但仍然在努力抓住它。使用Multipart上傳圖像並將多部分對象作爲參數發佈到彈簧mvc控制器

基本上我是一個ios開發者,我們有一個春季後端。我需要將圖像作爲多部分對象發送,因爲它需要作爲參數存儲在後端。

我正在閱讀AFNetworking,但我仍然不確定。後端是在應用程序設計(後端外包)之前創建的,所以現在我試圖連接到那裏。

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

我嘗試下面的代碼阿南德ķ但我現在在應對越來越HTTP Status 500這:

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

以及其他一些「垃圾」

新的基於更新在阿德南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

回答

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); 
}]; 
+0

你能解決這個問題嗎? – Kikers25

+0

@ Kikers25如果我能記得上面的答案確實有效 – DevC

相關問題