今天项目,发现图片上传这个多次用到,记录一下,以备后用
MBProgressHUD *hud = [MBProgressHUD showProcessHUD:@"" process:0];
NSDictionary *dic = @{@"type" : @"img", @"uploadLableName" : @"pic"};
NSString *postUrl = [NSString stringWithFormat:@"upload.url"];
AFHTTPRequestOperationManager* _manager = [AFHTTPRequestOperationManager manager];
NSMutableURLRequest* request = [_manager.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:postUrl parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:fileData name:@"pic" fileName:@".jpg" mimeType:@"image/png"];
} error:nil];
AFHTTPRequestOperation *operation = [_manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
if (200 == [responseObject[@"status"] integerValue]) {
success(responseObject);
}else
{
[MBProgressHUD showMessage:[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"message"]]];
}
[hud hide:YES];
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
[hud hide:YES];
[MBProgressHUD showMessage:@"上传失败!"];
}];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
hud.progress = (float)totalBytesWritten/totalBytesExpectedToWrite;
}];
[operation start];