如何在NSURLSession ios中使用multipart发布图像?

时间:2017-03-11 15:31:50

标签: ios objective-c image-uploading multipartform-data

您好我正在尝试使用NSURLSession将图像通过multipart上传到目标c中的服务器。但我得到的错误很少 org.apache.commons.fileupload.FileUploadException:标题部分有超过10240个字节(可能没有正确终止)

以下是我的目标c代码:

{

NSString *boundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";

NSString *fileParamConstant  = @"photo";

NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]];

[req setHTTPMethod:@"POST"];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data;boundary=%@",boundaryConstant];
[req setValue:contentType forHTTPHeaderField:@"Content-Type"];

NSMutableData *body = [NSMutableData data];

if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParamConstant, fileName] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

    NSString *bodyLength = [NSString stringWithFormat:@"%zu",[body length]];
    [req setValue:bodyLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPBody:body];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:nil delegateQueue:nil];

    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:req fromData:body completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
          NSLog(@"STRING %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    [uploadTask resume];
}

}

非常感谢任何帮助。

由于

0 个答案:

没有答案