简体   繁体   English

将图像从swift上传到php服务器时出错

[英]error uploading image from swift to php server

I have a problem trying to upload an image in swift to a PHP server. 我试图将swift中的图像上传到PHP服务器时遇到问题。 Everything looks good till the php processes the file. 一切看起来都很好,直到php处理文件。 In that moment I get the error. 在那一刻,我得到了错误。

The relevant part of the swift code is: 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)"
}

And the php is 而且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>";
?>

And last, the error I get is: 最后,我得到的错误是:

****** response data = ******响应数据=

Upload failed 上传失败

Here is some more debugging info:Array
(
    [file] => Array
        (
            [name] => Optional(\"boda20160428_135709.jpg\")
            [type] => 
            [tmp_name] => 
            [error] => 1
            [size] => 0
        )

)

Any tip would be very much appreciated. 任何小费都会非常感激。

It looks like Marc B has commented with the answer which is that it is a PHP file upload size issue. 看起来Marc B评论的答案是PHP文件上传大小问题。

However in cases like this it is worth testing each link in the chain separately. 但是在这种情况下,值得分别测试链中的每个链接。 For example testing and reviewing the output of createBodyWithParameters. 例如,测试和查看createBodyWithParameters的输出。 Create a test and run it there to check that the headers are properly formed. 创建一个测试并在那里运行它以检查标头是否正确形成。 Especially make sure that the string encoding is correct. 特别要确保字符串编码正确。 I'm not familiar with the appendString method on NSMutableData . 我不熟悉NSMutableData上的appendString方法。

It should be possible to feed that output more directly into the server to eliminate other potential issues. 应该可以将该输出更直接地提供给服务器以消除其他潜在问题。

The correct answer is that the image is too big and you need to compress the image before uploading it, using this 正确答案是图像太大,您需要在上传之前压缩图像,使用它

 UIImageJPEGRepresentation(image,0.2)

When the image is small enough you will get your tmp name 当图像足够小时,您将获得您的tmp名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM