编辑:好的,我只是将内容类型 header 设置为 multipart/form-data 没有区别。我的原始问题如下:
这是我关于堆栈溢出的第一个问题,我希望我做对了。
我只是在学习 Objective-C,最近完成了斯坦福类(class)的在线版本。我对 php 和 html 几乎一无所知。我使用的 php 脚本和 html 大部分是从教程中复制的。 Obj-C 对我来说更有意义。
问题:
我有一个 PHP 脚本。它上传图像文件。从服务器上同一文件夹中的 html 文件调用时,它可以正常工作。当从我的 obj-c 调用它时,我试图让相同的脚本工作。它似乎运行,它返回 200,obj-c 确实调用了 php,但是在线文件夹中没有文件出现。
网上好像很少介绍这个,因为它是ios7才引入的。我没有找到处理文件上传的例子,它们都处理下载,只是说上传是相似的。我所做的似乎满足我找到的任何教程。
我所知道的是:
可能重要的事情:
这里是 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/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我有一个奇怪的问题:我在rvm上安装了rubyonrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信