上传使用零字节文件大小的NSURLRequest结果的文件(Uploading a file usi

2019-09-16 10:05发布

我试图做用客观的C和的NSURLRequest一个简单的文件上传。

我目前(或多或少一派,放在一起)代码:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://127.0.0.1:8000/api/upload/"]];
[request setHTTPMethod:@"POST"];


NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];


NSMutableData *postData = [NSMutableData data]; 
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// Append the Usertoken
[postData appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"token\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:@"Content-Type: application/json\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithFormat:@"%@", token] dataUsingEncoding:NSUTF8StringEncoding]];

// Append the file
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%@\"\r\n", file]dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

// Close
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// Append
[request setHTTPBody:postData];

具有零字节的文件大小所有上传的文件。 在服务器端部分是否正常工作。 测试了卷曲。

难道我忘了什么东西?

Answer 1:

发现我的错误。 是一个非常简单的,偶然的,因为我缺乏有关HTTP知识。

我忘了追加八位字节流后的文件数据

NSData *photo = [[NSFileManager defaultManager] contentsAtPath:file];

// Append the file
[postData appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
[postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"fileupload\"; filename=\"%@\"\r\n", file]dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[NSData dataWithData:photo]];


文章来源: Uploading a file using NSUrlRequest results in Zero Bytes filesize