我正在尝试使用 ASIFormDataRequest 将文件上传到服务器(从自定义 mac os 应用程序)。在我的 cocoa/obj-c 代码中,我有:
- (IBAction)uploadFile:(id)sender
{
[networkQueue reset];
[networkQueue setShowAccurateProgress:YES];
[networkQueue setUploadProgressDelegate:progressIndicator];
[networkQueue setRequestDidFailSelector:@selector(postFailed:)];
[networkQueue setRequestDidFinishSelector:@selector(postFinished:)];
[networkQueue setDelegate:self];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:@"http://domain.com/to/upload.php"]] autorelease];
[request setFile:@"/path/to/file.jpg" forKey:@"file"];
[networkQueue addOperation:request];
[networkQueue go];
}
- (void)postFinished:(ASIHTTPRequest *)request
{
NSLog(@"Post Success");
}
- (void)postFailed:(ASIHTTPRequest *)request
{
NSLog(@"Post Failed");
}
服务器上的 PHP 代码如下所示:
$target_path = "files/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
当我尝试使用此代码上传文件时,我在客户端收到“成功后”响应,但该文件从未显示在我的服务器上。为了以防万一,我已将文件夹 CHMOD 为 777,但它似乎仍然不起作用。有人有建议,或者看到我处理这个问题的方式有错误吗?
谢谢!
最佳答案
为 future 的读者更新。这里的根本问题是您必须完全像这样创建 ASIFormDataRequest 项:
NSURL *url = [NSURL URLWithString:@"https://www.you.com/cgi-bin/you.cgi?stuff"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
不要添加更多release、retain、autorelease、self.等等!仅此而已。
嗯。我不完全确定那里的自动释放是正确的。您必须小心,不要丢失 ASIHttpRequest 中的结果指针。
抛开这一点,是否值得首先将其作为一个简单(非排队、异步)请求来尝试,完全使用这个已经被测试了数十亿次的模式:
-(void) sendSomethingAnything
{
NSURL *url = [NSURL URLWithString:@"https://www.you.com/cgi-bin/you.cgi?stuff"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"fakeIDstring" forKey:@"id"];
[request setPostValue:@"anotherCalue" forKey:@"username"];
// your file here ..
[request setDelegate:self];
[request setDidFinishSelector:@selector(postFinished:)];
[request setDidFailSelector:@selector(postFailed:)];
[request startAsynchronous];
}
只需粘贴您的网址即可立即尝试。这将消除很多问题,让我们更接近问题所在。在完成的例程中,获取并显示这样的结果...
NSData *newStringData = [request responseData];
NSString *x = [[[NSString alloc] initWithData:newStringData
encoding:NSUTF8StringEncoding] autorelease];
NSLog(@"result text from server is %@", x);
最后在你的 PHP 中。我发现添加一行代码很有用,该代码从 php 向我发送电子邮件,说明到底发生了什么。或者,使用“wall”命令,并在使用客户端时在服务器上打开一个 shell。这是了解工作时到底发生了什么的唯一方法。
(事实上,我使用老式的 Perl 而不是 future 派的 php,所以我无法提供任何相关代码!:) )
关于php - ASIFormDataRequest + PHP 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4362303/