通过swift在db mysql上保存图像

时间:2015-02-03 20:59:41

标签: php mysql image

我的php文件有问题。 我正在尝试通过xcode将图像上传到mysql db。

这是快速代码

let image = UIImage(named: "image.jpg")

    var imageData = UIImageJPEGRepresentation(image, 1)

    if imageData != nil{
        var request = NSMutableURLRequest(URL: NSURL(string:"link php file")!)
        var session = NSURLSession.sharedSession()

        request.HTTPMethod = "POST"

        var boundary = NSString(format: "---------------------------14737809831466499882746641449")
        var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
        request.addValue(contentType, forHTTPHeaderField: "Content-Type")

        var body = NSMutableData.alloc()


        // Image
        body.appendData(NSString(format: "--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(NSString(format:"Content-Disposition: attachment; name=\"userfile\"; filename=\"img.jpg\"").dataUsingEncoding(NSUTF8StringEncoding)!)
        //body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(imageData)
        body.appendData(NSString(format: "\r\n--%@--\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)

        request.HTTPBody = body

        var returnData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)

        var returnString = NSString(data: returnData!, encoding: NSUTF8StringEncoding)

        println("returnString \(returnString)")

    }

这里是php代码:

$myparam = $_FILES['userfile']; //getting image Here //getting textLabe Here 

$target_path = "uploads/".basename($myparam['filename']);  

if(move_uploaded_file($myparam['tmp_name'], $target_path)){
    $var = 1; 
} 
else {
    $var = 0; 
} 

$myarray = array("response" => $var, "path" => $target_path);
$out = json_encode($myarray);
echo($out);

问题出在路径上。它返回错误的路径,所以我在“uploads”文件夹中找不到图像。如果我在php文件中更改target_path(例如$ target_path =“uploads / image.jpg”),则会保存图像。

我认为这是一个非常容易的问题,但我不明白我必须改变什么。

感谢您的帮助

0 个答案:

没有答案