gpt4 book ai didi

objective-c - 使用 NSUrlRequest 上传文件导致零字节文件大小

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:07 25 4
gpt4 key购买 nike

我正在尝试使用 objective-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];

所有上传的文件都具有零字节文件大小。服务器端部分工作正常。使用 cURL 测试。

我是不是忘记了什么?

最佳答案

发现我的错误。这是一个非常简单的问题,因为我对 http 缺乏了解。

我忘记在octet-stream后面追加文件数据了

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]];

关于objective-c - 使用 NSUrlRequest 上传文件导致零字节文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10076493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com