2
我试图上传一个swift图像到PHP服务器时出现问题。一切看起来很好,直到php处理文件。在那一刻,我得到了错误。从swift上传图像到php服务器的错误
的SWIFT代码的相关部分是:
func myImageUploadRequest(image: UIImage, realfilename: String)
{
let myUrl = NSURL(string: "http://www.ignistudios.com/boda/postImage.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let param = [
"firstName" : "username",
"lastName" : "lastname",
"userId" : "9"
]
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(image, 1)
print(imageData.debugDescription)
if(imageData==nil) { return; }
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", realfilename: realfilename, imageDataKey: imageData!, boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("****** response data = \(responseString!)")
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, realfilename: String?, imageDataKey: NSData, boundary: String) -> NSData {
var body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = realfilename
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
而且PHP是
<?php
$uploaddir = '/fotos/';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
而在去年,我得到的错误是:
******响应数据=
上传失败
Here is some more debugging info:Array ( [file] => Array ( [name] => Optional(\"boda20160428_135709.jpg\") [type] => [tmp_name] => [error] => 1 [size] => 0 ))
任何提示将非常感激。
RTFM? http://php.net/manual/en/features.file-upload.errors.php错误#1 =文件大小超过php.ini中设置的限制 –