尝试将swift中的图像上传到PHP服务器时遇到问题。一切看起来都很好,直到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 ))
任何提示都会非常感激。
答案 0 :(得分:0)
看起来Marc B评论的答案是PHP文件上传大小问题。
然而,在这种情况下,值得分别测试链中的每个链接。例如,测试和查看createBodyWithParameters的输出。创建一个测试并在那里运行它以检查标头是否正确形成。特别要确保字符串编码正确。我不熟悉appendString
上的NSMutableData
方法。
应该可以将该输出更直接地输入服务器,以消除其他潜在问题。
答案 1 :(得分:0)
正确答案是图片太大,您需要在上传之前压缩图片,使用此
UIImageJPEGRepresentation(image,0.2)
当图像足够小时,您将获得您的tmp名称