iOS 上传表单文件(form-data 上传图片)

2019-04-09  本文已影响0人  阶梯
UIImage *image = [UIImage imageName:@"text.png"];
//下面是iOS两种获取图片的方法,一种获取为jpeg,一种获取为png
//转为jpeg上传可以让图片的大小压缩
//NSDate *imageData = UIImageJPEGRepresentation(_iconImg.image, 0.5); //0.5是压缩的比例
NSData *imageData = UIImagePNGRepresentation(image);

NSString *temp = @"http://202.103.160.153:1940/tools/upload_ajax.ashx";

//NSString *url = [temp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:temp parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    //参数name:是后台给你的图片在服务器上字段名;
    //参数fileNmae:自己起得一个名字,
    //参数mimeType:这个是决定于后来接收什么类型的图片,接收的时png就用image/png ,接收的时jpeg就用image/jpeg
    [formData appendPartWithFileData:imageData name:@"Filedata" fileName:@"Filedate.png" mimeType:@"image/png"];
    
} error:nil];


AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

//设置服务器返回内容的接受格式
AFHTTPResponseSerializer *responseSer = [AFHTTPResponseSerializer serializer];
responseSer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
manager.responseSerializer = responseSer;

NSProgress *progress = nil;

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    
    if (error) {
        NSLog(@"Error: %@", error);    

    } else {
        
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        NSLog(@"%@\n %@", response, str);
        
    }
    
}];

[uploadTask resume];
上一篇下一篇

猜你喜欢

热点阅读