如何将文档文件上传到服务器,即pdf / doc / docx文件

时间:2016-10-29 06:14:12

标签: ios json xcode file-upload server

我尝试上传文件,就像我们将图片上传到服务器一样,但它并不成功。以下是我尝试过的代码。

NSDictionary *params =@{@"cadidateid":canid, @"can_ resume_title":self->Nameoffile.text};

NSString *path = [URLOFFILE path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];

NSString *urlString = [NSString stringWithFormat:@"URL"];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSString *kNewLine = @"\r\n";
NSMutableData *body = [NSMutableData data];

for (NSString *namess in params.allKeys) {
    NSData *values = [[NSString stringWithFormat:@"%@", params[namess]] dataUsingEncoding:NSUTF8StringEncoding];

    [body appendData:[[NSString stringWithFormat:@"--%@%@", boundary, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"", namess] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@%@", kNewLine, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:values];
    [body appendData:[kNewLine dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"can_resume\"; filename=\"test.pdf\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:data]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setHTTPBody:body];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

0 个答案:

没有答案