我正在尝试将图片发布到网络服务器,由于某种原因,文件被损坏并且大小为(102)
我在论坛上进行了搜索,但找不到解决问题的方法。 任何帮助都会得到祝福!
我的代码如下:
- (void)postItemImage:(UIImage*)image withKey:(NSString*)key andItemid:(int)itemId;
{
NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
NSLog(@"inside postItemImage");
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:kBasePostUrl]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449"
;
NSData *boundryData = [[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:boundryData];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"Request\"\r\n\r\n%@", @"addItemMedia"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:boundryData];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"picture\"; filename=\"swapper.jpg\"; \r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:boundryData];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:boundryData];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:boundryData];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userId\"\r\n\r\n%d", [[NSUserDefaults standardUserDefaults] integerForKey:kUserIDKey]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:boundryData];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"itemId\"\r\n\r\n%d", itemId] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:boundryData];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"itemMediaType\"\r\n\r\n%@", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:boundryData];
[request setHTTPBody:body];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSLog(@"Do in background");
//Do in background
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (returnData) {
dispatch_sync(dispatch_get_main_queue(), ^{
//Do in Main thread
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"return: %@", returnString);
[self.delegate uploadFinishedWithResponse:returnString];
});
}
});
}
答案 0 :(得分:0)
当您传输图像时,我建议使用base64。
您应该从发件人对其进行编码,然后在另一方进行解码。
网上有很多关于如何编码/解码base64的教程。