文件上传的步骤
//先创建一个request
NSURL *url = [NSURL URLWithString:@""];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
1.设置请求头
*目的:告诉服务器请求体里面的内容并非普通参数,而是包含了文件参数
NSString *boundary = @"UploadBoundary";//设置请求体参数的分隔符(请求体分隔符必须在此前面加上两个-)
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
2.设置请求体
*作用:存放参数(文件参数和非文件参数)
1>非文件参数
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposision: form-data: name=\"参数名\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"参数值" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
2>文件参数
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"参数名\"; filename=\"文件名\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: 文件类型\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithContentsOfFile:@""]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
3>结尾标记
*作用:告诉请求体参数已拼接完成
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
request.HTTPBody = body;
request设置完毕后,就可以发送请求了
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//这里就和普通请求一样了
}];
使用NSURLConnection上传文件例子
/**
上传文件
@param url 地址
@param fileName 上传到服务器的文件名称
@param fileData 文件数据
@param mimeType 文件类型
@param params 非文件参数
*/
- (void)uploadWithUrl:(NSString *)url fileName:(NSString *)fileName fileData:(NSData *)fileData mimeType:(NSString *)mimeType params:(NSDictionary *)params{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
//设置请求头
NSString *boundary = @"UploadBoundary";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
//设置请求体
NSMutableData *body = [NSMutableData data];
//非文件参数
[params enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *disposision = [NSString stringWithFormat:@"Content-Disposision: form-data: name=\"%@\"\r\n",key];
[body appendData:[disposision dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[obj description] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}];
//文件参数
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",fileName] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n",mimeType] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:fileData];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//结果标记
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
request.HTTPBody = body;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
}];
}
使用AFN框架上传图片例子
NSString *urlString = @"";
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//普通参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:@"张三" forKey:@"username"];
[mgr POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@""]);
/**
拼接文件参数
@fileData : 要上传的文件数据
@name : 后台定义文件的参数名
@fileName : 上传到服务器的文件名称
@mimeType : 上传的文件类型
*/
[formData appendPartWithFileData:imageData name:@"file" fileName:@"text.png" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
获取文件的MIMEType
/**
获取文件的MIMEType
@param url 文件路径
@return 文件MIMEType
*/
- (NSString *)MIMEType:(NSURL *)url{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
return response.MIMEType;
}
有时候项目需要要一次上传多张图片,可以将图片压缩成一个zip包,然后上传这样的方式来处理。文件压缩和解压工具SSZipArchive