无法使用 AFNetworking 上传 PIC

Cannot upload a PIC using AFNetworking

提问人:Cp Jiang 提问时间:11/23/2021 更新时间:11/24/2021 访问量:36

问:

我可以在 Postman 和 swagger 中上传 PIC。我需要在 Header 中设置 @{@“Content-Type”: @“multipart/form-data”}。 但是在OC程序中,这是一些错误。帮助!!

  NSString *urlString =@"http://192.168.1.1/upload";
  UIImage *image = [UIImage imageNamed:@"camp.jpg"];
  NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
  NSLog(@"上传图片的样子:%@", imageData);

  NSDictionary *parameters = @{@"file":@"camp.jpg"};

   AFHTTPSessionManager *manager1 = [AFHTTPSessionManager manager];
   manager1.requestSerializer = [AFJSONRequestSerializer serializer];   // 请求JSON格式
   manager1.responseSerializer = [AFJSONResponseSerializer serializer]; // 响应JSON格式
manager1.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json;charset=UTF-8", nil];

[manager1 POST:urlString parameters:parameters headers:@{@“Content-Type”: @“multipart/form-data”} constructingBodyWithBlock:^(id _Nonnull formData) {

    [formData appendPartWithFileData:imageData name:@"file" fileName:@"camp.jpg" mimeType:@"image/jpeg"];
 
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
    NSLog(@"上传成功:%@", responseObject);

    
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
    NSLog(@"上传失败:%@", error);
}];

错误是:

错误域=com.alamofire.error.serialization.response 代码=-1011“请求失败:内部服务器错误(500)” UserInfo={NSLocalizedDescription=请求失败:内部服务器错误(500),NSUnderlyingError=0x2833b5e90{错误域=com.alamofire.error.serialization.response代码=-1016“请求失败:不可接受的内容类型:application/json” UserInfo={NSLocalizedDescription=请求失败:不可接受的内容类型:application/json,NSErrorFailingURLKey=http://www.sample.com:18081/camping/file/v1/pic/upload,com.alamofire.serialization.response.error.data={length = 347, bytes = 0x7b227469 6d657374 616d7022 3a223230 ...75706c6f 6164227d }, com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x283cb67c0> { URL: http://192.168.1.1/upload } { 状态代码: 500, 标头 { 连接 = ( 关闭 ); “内容类型” = ( “应用程序/json;字符集 = UTF-8” ); 日期 = ( “星期二, 23 11月 2021 0 2021-11-23 11:10:20.853300+0800 Campingsitedemo[76232:4244771] [UICollectionViewRecursion] cv == 0x105a5f400 禁用递归触发器日志记录 2021-11-23 11:10:51.172438+0800 Campingsitedemo[76232:4245042] [tcp] tcp_input [C10.1:2] flags=[R.] seq=2019602476,ack=0,win=64240 state=TIME_WAIT rcv_nxt=2019602983,snd_una=2071941654

文件上传 afnetworking

评论


答:

0赞 Cp Jiang 11/24/2021 #1

更改为 AFHTTPRequestSerializer

manager.requestSerializer = [AFHTTPRequestSerializer 序列化器]; manager.responseSerializer = [AFHTTPResponseSerializer 序列化器];

现在没事了