图片正常上传到服务器,而且上传图片的大小能根据需求要确定,可以自行选择图片需要压缩的大小范围。
1、AFNetworking可选择单张或多张图片上传
- (void)uploadImag:(NSArray*)imgArr success:(HCSucccess)success failuer:(HCFailure)failure{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manage POST:[NSStringstringWithFormat:@"%@%@",HCAllURLHead,url] parameters:@{} constructingBodyWithBlock:^(id_NonnullformData) {
for(UIImage*image in imgArr) {
//NSData *data = UIImageJPEGRepresentation(image, 0.8);
NSData*data = [selfcompressOriginalImage:imagetoMaxDataSizeKBytes:1000];//[self scaleImageData:image];
// 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题,
// 可以在上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateString = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.jpg", dateString];
/*
*该方法的参数
1. appendPartWithFileData:要上传的照片[二进制流]
2. name:对应网站上[upload.php中]处理文件的字段(比如upload)
3. fileName:要保存在服务器上的文件名
4. mimeType:上传的文件的类型
*/
[formData appendPartWithFileData:dataname:[NSStringstringWithFormat:@"uploadImg%ld",(unsignedlong)[imgArrindexOfObject:image]]fileName:[NSStringstringWithFormat:@"uploadImg%ld.jpg",(unsignedlong)[imgArrindexOfObject:image]]mimeType:@"image/jpg"];
}
}progress:^(NSProgress*_NonnulluploadProgress) {
}success:^(NSURLSessionDataTask*_Nonnulltask,id_NullableresponseObject) {
NSDictionary*dict;
if([responseObjectisKindOfClass:[NSDictionaryclass]]) {
dict = responseObject;
}elseif([responseObjectisKindOfClass:[NSDataclass]]){
dict = [NSJSONSerializationJSONObjectWithData:responseObjectoptions:0error:nil];
}
}failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror) {
}];
}
2、压缩图片方法,可定义到压缩的大小
- (NSData*)compressOriginalImage:(UIImage*)image toMaxDataSizeKBytes:(CGFloat)size{
NSData* data =UIImageJPEGRepresentation(image,1.0);
CGFloatdataKBytes = data.length/1000.0;
CGFloatmaxQuality =0.9f;
CGFloatlastData = dataKBytes;
CGFloatminQuality =0.06f;
if(dataKBytes >=3000&& dataKBytes <6000) {
minQuality =0.1;
}elseif(dataKBytes >=6000&& dataKBytes >9000) {
minQuality =0.2;
}elseif(dataKBytes >=9000) {
minQuality =0.3;
}
while(dataKBytes > size && maxQuality > minQuality) {
maxQuality = maxQuality - minQuality;
data =UIImageJPEGRepresentation(image, maxQuality);
dataKBytes = data.length/1000.0;
if(lastData == dataKBytes) {
break;
}else{
lastData = dataKBytes;
}
}
returndata;
}