其中需要注意的是:
[headerStrM appendFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n",formName,reName];
需要按照后端的要求,把name填写正确。
以下是完整代码:
+ (void)httpUpload:(NSString *)urlStr filePath:(NSString *)filePath succ:(void (^)(NSDictionary *dataInfo))succ fail:(void (^)(NSError *error))fail {
if (!urlStr || urlStr.length <= 0) {
return;
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlStr]];
request.HTTPMethod = @"POST";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", kFHUploadFileBoundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSString *fileNameStr = [filePath lastPathComponent];
NSData *bodyData = [self getHttpBodyWithFilePath:filePath formName:@"singleFile" reName:fileNameStr];
[request setHTTPBody:bodyData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
} else {
}];
[uploadTask resume];
}
/// filePath:要上传的文件路径 formName:表单控件名称 reName:上传后文件名
+ (NSData *)getHttpBodyWithFilePath:(NSString *)filePath formName:(NSString *)formName reName:(NSString *)reName {
NSMutableData *data = [NSMutableData data];
NSString *fileType = [self fileMIMETypeURLSessionWithPath:filePath];
NSMutableString *headerStrM = [NSMutableString string];
[headerStrM appendFormat:@"--%@\r\n", kFHUploadFileBoundary];
// name:表单控件名称 filename:上传文件名
[headerStrM appendFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n",formName,reName];
[headerStrM appendFormat:@"Content-Type: %@\r\n\r\n",fileType];
[data appendData:[headerStrM dataUsingEncoding:NSUTF8StringEncoding]];
// 文件内容
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
[data appendData:fileData];
NSMutableString *footerStrM = [NSMutableString stringWithFormat:@"\r\n--%@--\r\n", kFHUploadFileBoundary];
[data appendData:[footerStrM dataUsingEncoding:NSUTF8StringEncoding]];
return data;
}
+ (NSString *)fileMIMETypeURLSessionWithPath:(NSString *)path {
NSURL *url = [NSURL fileURLWithPath:path];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block NSString *mimeType = nil;
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
mimeType = response.MIMEType;
dispatch_semaphore_signal(semaphore);
}];
[task resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return mimeType;
}
网友评论