我正在尝试使用AFNetworking库上传图像,它是发布请求,该图像应该在正文中。我将其转换为NSData并尝试发送,但是它没有用,所有我从后端人员那里得到的图像格式都应该是图像文件。
我的代码如下:
+(void)imageUpload:(NSMutableDictionary *)imageData :(void(^)(BOOL success,NSError *error,NSString *path))block{
NSString *urlString = [baseUrl stringByAppendingString:@"Media/ImageUpload"];
NSMutableDictionary *parameters = [NSMutableDictionary new];
[parameters setObject:[self getXsession] forKey:@"x-session"];
UIImage *image = [imageData objectForKey:@"image"];
NSData *imgData = UIImagePNGRepresentation(image);
NSMutableDictionary *bodyImage = [NSMutableDictionary new];
[bodyImage setObject:imgData forKey:@"image"];
[bodyImage setObject:@"leads_temp" forKey:@"folder"];
[self makePostRequestWithUrl:urlString parameters:parameters body:bodyImage headers:nil updateXsession:NO completionBlock:^(NSError *error, id responseObject) {
BOOL success = [responseObject[@"meta"][@"status"]isEqualToString:@"OK"]?YES:NO;
if(success){
NSString *path = responseObject[@"response"][@"path"];
if (block){
block(success,nil,path);
}
}else {
if (block){
block(NO,error,nil);
}
}
}];
}
发布请求:
+(void)makePostRequestWithUrl:(NSString *)url parameters:(NSMutableDictionary *)parameters body:(NSMutableDictionary*)body headers:(NSDictionary *)headers updateXsession:(BOOL)shouldUpdate completionBlock:(void(^)(NSError *error, id responseObject))block {
NSError *error;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:parameters error:&error];
request.timeoutInterval = 30;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
stringWithFormat:@"%@\n%@\n%@",tableValue,jsonString,@"}"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSHTTPURLResponse *myResponse = (NSHTTPURLResponse *)response ;
if (myResponse && shouldUpdate) {
//do some stuffs
}
if (block) {
block(error, responseObject);
}else {
block(responseObject, error);
return ;
}
}]resume];
}
您知道解决方案是什么吗? 谢谢。
答案 0 :(得分:1)
尝试一下。
R.folder_name.file_name