douzuan5365 2016-04-28 14:31
浏览 90
已采纳

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

I have a problem trying to upload an image in swift to a PHP server. Everything looks good till the php processes the file. In that moment I get the error.

The relevant part of the swift code is:

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)
")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"

")
            body.appendString("\(value)
")
        }
    }

    let filename = realfilename

    let mimetype = "image/jpg"

    body.appendString("--\(boundary)
")
    body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"
")
    body.appendString("Content-Type: \(mimetype)

")
    body.appendData(imageDataKey)
    body.appendString("
")



    body.appendString("--\(boundary)--
")

    return body
}




func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"
}

And the php is

<?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.
";
} 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.

  • 写回答

2条回答 默认 最新

  • dp610807 2016-04-28 15:43
    关注

    It looks like Marc B has commented with the answer which is that it is a PHP file upload size issue.

    However in cases like this it is worth testing each link in the chain separately. For example testing and reviewing the output of 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.

    It should be possible to feed that output more directly into the server to eliminate other potential issues.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示