编辑:好的,我只是将内容类型 header 设置为 multipart/form-data 没有区别。我的原始问题如下:
这是我关于堆栈溢出的第一个问题,我希望我做对了。
我只是在学习 Objective-C,最近完成了斯坦福类(class)的在线版本。我对 php 和 html 几乎一无所知。我使用的 php 脚本和 html 大部分是从教程中复制的。 Obj-C 对我来说更有意义。
问题:
我有一个 PHP 脚本。它上传图像文件。从服务器上同一文件夹中的 html 文件调用时,它可以正常工作。当从我的 obj-c 调用它时,我试图让相同的脚本工作。它似乎运行,它返回 200,obj-c 确实调用了 php,但是在线文件夹中没有文件出现。
网上好像很少介绍这个,因为它是ios7才引入的。我没有找到处理文件上传的例子,它们都处理下载,只是说上传是相似的。我所做的似乎满足我找到的任何教程。
我所知道的是:
- 当从服务器上的 html 文件调用时,php 工作,文件被上传
- obj-c 肯定在调用 php 脚本(我在 php 中写入了一些日志记录(使用 file_put_contents)以确认当我运行 obj-c 时正在调用脚本)
- obj-c 几乎肯定在上传图像文件(如果我在 obj-c 中使用委托(delegate)方法,它会显示上传进度)
- 但是 php 脚本没有收到文件(我写入 php 的日志显示 $_FILES 没有值,当从 obj-c 调用时。当从 html 调用时,它按预期工作)
- 我刚刚编辑了 php 以记录它收到的 header ,它确实获得了图像文件的 Content-Length。
可能重要的事情:
- 我没有添加任何 html header ,我看到的教程中没有说我必须(使用 NSURLSessionUploadTask),我假设 NSURLSessionUploadTask 会为您解决这个问题?或者这是我的问题?
- [响应描述] 返回 200,引用:{ URL:(PHP 脚本 URL)} { 状态代码:200,标题 { 连接=“保持事件”; “内容类型”=“文本/html”; Date = "2014 年 1 月 16 日星期四 19:58:10 GMT"; "Keep-Alive"= "超时=5, 最大值=100"; 服务器= Apache ; “传输编码”=身份; }
- html 指定了 enctype="multipart/form-data",也许这必须在我的 obj-c 某处工作?
- 到目前为止,我只是在模拟器上运行它
- 任何帮助将不胜感激!谢谢:)
- 编辑,我只是编辑了下面的代码以显示 [request setHTTPMethod:@"POST"] 而不是我原来的 [request setHTTPMethod:@"PUSH"],但它没有改变。
这里是 objective-c
- (void) uploadFile: (NSURL*) localURL toRemoteURL: (NSURL*) phpScriptURL
{
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:phpScriptURL];
[request setHTTPMethod:@"POST"];
NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:localURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if (error == nil)
{
NSLog(@"NSURLresponse =%@", [response description]);
// do something !!!
} else
{
//handle error
}
[defaultSession invalidateAndCancel];
}];
self.imageView.image = [UIImage imageWithContentsOfFile:localURL.path]; //to confirm localURL is correct
[uploadTask resume];
}
这是服务器上的 PHP 脚本
<?php
$file = 'log.txt';
$current = file_get_contents($file);
$current .= $_FILES["file"]["name"]." is being uploaded. "; //should write the name of the file to log.txt
file_put_contents($file, $current);
ini_set('display_errors',1);
error_reporting(E_ALL);
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
//&& ($_FILES["file"]["size"] < 100000) //commented out for error checking
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
if (move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]))
{
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
else
{
echo "Error saving to: " . "upload/" . $_FILES["file"]["name"];
}
}
}
}
else
{
echo "Invalid file";
}
?>
这里是调用相同脚本时按预期工作的 html 文件
<html>
<body>
<form action="ios_upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
最佳答案
我刚刚在这里回答了同样的问题: https://stackoverflow.com/a/28269901/4518324
基本上,文件以二进制形式在请求正文中上传到服务器。
要在 PHP 中保存该文件,您只需获取请求正文并将其保存到文件即可。
您的代码应如下所示:
Objective-C 代码:
- (void) uploadFile: (NSURL*) localURL toRemoteURL: (NSURL*) phpScriptURL
{
// Create the Request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:phpScriptURL];
[request setHTTPMethod:@"POST"];
// Configure the NSURL Session
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.upload"];
[sessionConfig setHTTPMaximumConnectionsPerHost: 1];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:nil];
NSURLSessionUploadTask* uploadTask = [defaultSession uploadTaskWithRequest:request fromFile:localURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
if (error == nil)
{
NSLog(@"NSURLresponse =%@", [response description]);
// do something !!!
} else
{
//handle error
}
[defaultSession invalidateAndCancel];
}];
self.imageView.image = [UIImage imageWithContentsOfFile:localURL.path]; //to confirm localURL is correct
[uploadTask resume];
}
PHP 代码:
<?php
// Get the Request body
$request_body = @file_get_contents('php://input');
// Get some information on the file
$file_info = new finfo(FILEINFO_MIME);
// Extract the mime type
$mime_type = $file_info->buffer($request_body);
// Logic to deal with the type returned
switch($mime_type)
{
case "image/gif; charset=binary":
// Create filepath
$file = "upload/image.gif";
// Write the request body to file
file_put_contents($file, $request_body);
break;
case "image/png; charset=binary":
// Create filepath
$file = "upload/image.png";
// Write the request body to file
file_put_contents($file, $request_body);
break;
default:
// Handle wrong file type here
echo $mime_type;
}
?>
我在这里写了一个录制音频并将其上传到服务器的代码示例: https://github.com/gingofthesouth/Audio-Recording-Playback-and-Upload
它显示了从保存到 iOS 设备到上传并保存到服务器的代码。
希望对您有所帮助。
关于php - NSURLSessionUploadTask 没有将文件传递给 php 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21173231/