• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - 如何在发布数据iOS objective-c 中将图像附件发送到服务器

[复制链接]
菜鸟教程小白 发表于 2022-12-12 14:23:46 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

在 postman 中向服务器发送数据,但在 Objective-C 中出现错误。

image1

我试图从服务器上实现这个失败。我在下面提到的链接不起作用。获取错误上传失败。我做错了什么?

Upload image to server ios

how to POST value while uploading image in iOS objective c

我的代码:

NSData *dataImage = UIImageJPEGRepresentation(myImage, 1.0f);

// set your URL Where to Upload Image
NSString *urlString = @"http://xxxxxxxxxxxxxxxx/index.php/API/uploadClaim";

NSDictionary *user = [[NSUserDefaults standardUserDefaults] objectForKey"userDetails"];

// Create 'OST' MutableRequest with Data and Other Image Attachment.

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject"filename"  forKey"file_name"];
[_params setObject"photo"  forKey"file_type"];
[_params setObject:[[user objectForKey"user_data"] objectForKey"id"]  forKey"user_id"];

NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
NSString* FileParamConstant = @"image";

NSURL* requestURL = [NSURL URLWithString:urlString];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:120];
[request setHTTPMethod"OST"];

NSString *contentType = [NSString stringWithFormat"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params)
{
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
if (dataImage) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:dataImage];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
// set URL
[request setURL:requestURL];

NSURLResponse *response = nil;
NSError *requestError = nil;

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&requestError];



Best Answer-推荐答案


这是我上传一个或多个图像文件的工作代码:

请注意:您应该在具有正确键值的 NSDictionary 中传递图像/文件数据,并且您应该将键名称设置为您的服务器在上传调用中所期望的。
例如,在您的情况下,它是 file

parameters 字典将是您与 file

一起发送的其他参数
- (void) performNetworkEventRequestCallWithFileUpload NSMutableDictionary*) imagesData : (NSMutableDictionary*)parameters completionBlockvoid (^)(BOOL succeeded, NSDictionary *dict))completionBlock {


NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:BASE_URL]];
[urlRequest setHTTPMethod:@"OST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[urlRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];


[parameters enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSString *object, BOOL *stop) {
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@",object] dataUsingEncoding:NSUTF8StringEncoding]];
}];


[imagesData enumerateKeysAndObjectsUsingBlock: ^(NSString *key, NSData *object, BOOL *stop) {
    if ([object isKindOfClass:[NSData class]]) {
        if (object.length > 0) {
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            NSString *timeSTamp = [NSString stringWithFormat:@"%@",[NSDate date]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpg\"\r\n",key,timeSTamp] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[NSData dataWithDatabject]];
        }

    }
}];


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


AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = nil;

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
        completionBlock (NO, responseObject);
    } else {
        NSLog(@"success");
        completionBlock (YES, responseObject);
    }
}];
[dataTask resume];
}

关于ios - 如何在发布数据iOS objective-c 中将图像附件发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47874414/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap