Objective c 在Objective C中通过POST上传图像

Objective c 在Objective C中通过POST上传图像,objective-c,uiimage,http-post,Objective C,Uiimage,Http Post,我目前正在通过HTTPPOST将一个图像上传到服务器,但似乎无法找到一种方法来构建调用该服务的url。用户从库或相机中选择图像,然后调用执行insert语句的json服务 该服务需要以下模板: @"%@/DataTransfer/SetUserProfileImage?EMP_ID=%@&image=%@&imageName=%@" 它期望图像数据以某种方式转换为字符串并通过url发送 这是我当前的代码: - (BOOL)setUserProfileImage:(UIImage

我目前正在通过HTTPPOST将一个图像上传到服务器,但似乎无法找到一种方法来构建调用该服务的url。用户从库或相机中选择图像,然后调用执行insert语句的json服务

该服务需要以下模板:

@"%@/DataTransfer/SetUserProfileImage?EMP_ID=%@&image=%@&imageName=%@"
它期望图像数据以某种方式转换为字符串并通过url发送

这是我当前的代码:

- (BOOL)setUserProfileImage:(UIImage *)imgUser Name:(NSString *)strName{

    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    NSData *dataImage = UIImagePNGRepresentation(imgUser);

    NSString* theNSString = [[NSString alloc] initWithData:dataImage encoding:NSASCIIStringEncoding];

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/DataTransfer    /SetUserProfileImage?EMP_ID=%@&"
                                   "image=%@&imageName=%@",
                                   appDelegate.ServerAddress, 
                                   appDelegate.UserId,
                                   theNSString,
                                   strName]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url 
                                                       cachePolicy: NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];


    NSURLResponse* response = nil;
   NSError* resultError = nil;

   NSData* data = [NSURLConnection sendSynchronousRequest:request 
                                     returningResponse:&response 
                                                 error:&resultError];

   NSString *strResult = [[NSString alloc] initWithBytes:[data bytes] 
                                               length:[data length] 
                                             encoding:NSUTF8StringEncoding]; 

   BOOL imgResponse = [strResult boolValue];
   [strResult release];

   return imgResponse;
}
我得到一个错误,说NSURL是“”。似乎无法建立正确的URL。我知道服务本身再次将该字符串转换为图像

更新:

- (BOOL)setUserProfileImage:(UIImage *)imgUser Name:(NSString *)strName{

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

NSString *url = [NSString stringWithFormat:@"%@/DataTransfer/SetUserProfileImage",appDelegate.ServerAddress]; 

NSData *data = UIImagePNGRepresentation(imgUser);

NSString * boundary = @"tweetPhotoBoundaryParm";
NSMutableData *postData = [NSMutableData dataWithCapacity:[data length] + 1024];

name=\"EMP_ID\"\r\n\r\n%@", @"100-01"];
NSString * boundaryString = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary];
NSString * boundaryStringFinal = [NSString stringWithFormat:@"\r\n--%@--\r\n", boundary];


[postData appendData:[boundaryString dataUsingEncoding:NSUTF8StringEncoding]];    
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\";\r\nfilename=\"media.png\"\r\nContent-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:data];
[postData appendData:[boundaryStringFinal dataUsingEncoding:NSUTF8StringEncoding]];

NSMutableURLRequest * theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] 
                                                                            cachePolicy:NSURLRequestUseProtocolCachePolicy 
                                                                        timeoutInterval:60.0];

[theRequest setHTTPMethod:@"POST"];

[theRequest addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
//[theRequest addValue:@"www.tweetphoto.com" forHTTPHeaderField:@"Host"];
NSString * dataLength = [NSString stringWithFormat:@"%d", [postData length]];
[theRequest addValue:dataLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPBody:(NSData*)postData];

NSURLConnection * theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (theConnection)
{
    webData =[[NSMutableData data] retain];
}
else
{
    NSLog(@"%@",@"Could not connect to the network");
}

return false;
}

这种方法有几个问题

1) 将图像的原始字节转换为字符串永远不会起作用

NSData *dataImage = UIImagePNGRepresentation(imgUser);
NSString* theNSString = [[NSString alloc] initWithData:dataImage encoding:NSASCIIStringEncoding];
将失败。您将永远无法从
然后从字符串
重建
数据图像
。您需要对dataImage进行base64编码。使用类似的方法进行base64编码

2) 不要将图像数据放入URL。您需要将图像数据放在帖子正文中

3) 不要使用“application/x-www-form-urlencoded”,使用“multipart/form data”


评论后更新

很抱歉,但在理解您的系统方面,您似乎还有很多工作要做

在上面的示例中,您将所有数据添加到URL查询字符串中,但没有向消息体添加任何内容。在该示例中,您将内容类型设置为“application/x-www-form-urlencoded”

现在你似乎认为帖子应该是JSON格式的。你需要找出应该怎么做。该JSON消息需要如何附加?在你说数据需要在URL中之前,情况仍然是这样吗?如果需要将JSON消息附加到POST正文,POST的内容类型需要是什么?JSON消息的结构是什么(所需的所有键/值字段)


在任何人能够帮助您之前,您需要准确地找到所需的内容。应该有人能准确地描述HTTP消息。

Objective-C

-(void)saveImageToServer
{
    // COnvert Image to NSData
    NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:@"yourImage"], 1.0f);

    // set your URL Where to Upload Image
    NSString *urlString = @"Your URL HERE";

    // set your Image Name
    NSString *filename = @"YourImageFileName";

    // Create 'POST' MutableRequest with Data and Other Image Attachment.
    NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:dataImage]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];

    // Get Response of Your Request
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"Response  %@",responseString);
}
Swift

// COnvert Image to NSData
var dataImage: NSData = UIImageJPEGRepresentation(UIImage(named: "yourImage"), 1.0)
// set your URL Where to Upload Image
var urlString: String = "Your URL HERE"
// set your Image Name
var filename: String = "YourImageFileName"
// Create 'POST' MutableRequest with Data and Other Image Attachment.
var request: NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: urlString)!
request.HTTPMethod = "POST"
var boundary: String = "---------------------------14737809831466499882746641449"
var contentType: String = "multipart/form-data; boundary=\(boundary)"
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
var postbody: NSMutableData = NSMutableData.data()
postbody.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding))
postbody.appendData("Content-Disposition: form-data; name=\"userfile\"; filename=\"\(filename).jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding))
postbody.appendData(String.stringWithString("Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding))
postbody.appendData(NSData.dataWithData(dataImage))
postbody.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding))
request.HTTPBody = postbody
// Get Response of Your Request
var returnData: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
var responseString: String = String(data: returnData, encoding: NSUTF8StringEncoding)
NSLog("Response  %@", responseString)

它确实是空的。试着生成一个NSString,用NSLog打印它,当你得到正确的结果时,用它构建一个NSURL。图像数据是如何放在帖子正文中的?url是否希望图像位于url中有关系吗?NSMutableURLRequest有一个方法
-setHTTPBody:
。您需要使用此方法设置整个帖子正文。我猜您的后端系统结合了帖子正文和查询字符串参数,因此您只需要将图像数据放入帖子正文中。如果您确实有一个URL端点需要URL中的图像数据,那么您需要更改URL端点。我似乎不知道这是如何工作的,这是我在Web上找到的当前代码。我忘了提到服务希望主体在jsonHow中传递uiimage