@第一種:我的
#pragma mark - AFNetworking上傳文件
- (void)didClickUploadButtonAction{
NSString *fileName = @"hmt";
// 確定需要上傳的文件(假設選擇本地的文件)
NSURL *filePath = [[NSBundle mainBundle] URLForResource:fileName withExtension:@"png"];
NSDictionary *parameters = @{@"name":@"額外的請求參數"};
AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
[requestManager POST:@"http://192.168.10.18:8080/AFNetworkingServer/upload" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
/**
* appendPartWithFileURL // 指定上傳的文件
* name // 指定在服務器中獲取對應文件或文本時的key
* fileName // 指定上傳文件的原始文件名
* mimeType // 指定商家文件的MIME類型
*/
[formData appendPartWithFileURL:filePath name:@"file" fileName:[NSString stringWithFormat:@"%@.png",fileName] mimeType:@"image/png" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
[[[UIAlertView alloc] initWithTitle:@"上傳結果" message:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] delegate:self cancelButtonTitle:@"" otherButtonTitles:nil] show];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"獲取服務器響應出錯");
}];
}
@第二種:(朋友的)
NSData *imageData = UIImagePNGRepresentation(image);
//轉碼成UTF-8 否則可能會出現錯誤
NSString *URLTmp = [NSString stringWithFormat:@"%@%@",CGBaseURL,path];
NSString *URLTmps = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
URLTmp = URLTmps;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:URLTmp parameters:body constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData name:@"headerImg" fileName:@"123.png" mimeType:@"image/png"];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
block(responseObject);
}
}];
[uploadTask resume];